MCPcopy Index your code
hub / github.com/RustPython/RustPython / addpackage

Function addpackage

Lib/site.py:168–231  ·  view source on GitHub ↗

Process a .pth file within the site-packages directory: For each line in the file, either combine it with sitedir to a path and add that to known_paths, or execute it if it starts with 'import '.

(sitedir, name, known_paths)

Source from the content-addressed store, hash-verified

166
167
168def addpackage(sitedir, name, known_paths):
169 """Process a .pth file within the site-packages directory:
170 For each line in the file, either combine it with sitedir to a path
171 and add that to known_paths, or execute it if it starts with 'import '.
172 """
173 if known_paths is None:
174 known_paths = _init_pathinfo()
175 reset = True
176 else:
177 reset = False
178 fullname = os.path.join(sitedir, name)
179 try:
180 st = os.lstat(fullname)
181 except OSError:
182 return
183 if ((getattr(st, 'st_flags', 0) & stat.UF_HIDDEN) or
184 (getattr(st, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_HIDDEN)):
185 _trace(f"Skipping hidden .pth file: {fullname!r}")
186 return
187 _trace(f"Processing .pth file: {fullname!r}")
188 try:
189 with io.open_code(fullname) as f:
190 pth_content = f.read()
191 except OSError:
192 return
193
194 try:
195 # Accept BOM markers in .pth files as we do in source files
196 # (Windows PowerShell 5.1 makes it hard to emit UTF-8 files without a BOM)
197 pth_content = pth_content.decode("utf-8-sig")
198 except UnicodeDecodeError:
199 # Fallback to locale encoding for backward compatibility.
200 # We will deprecate this fallback in the future.
201 import locale
202 pth_content = pth_content.decode(locale.getencoding())
203 _trace(f"Cannot read {fullname!r} as UTF-8. "
204 f"Using fallback encoding {locale.getencoding()!r}")
205
206 for n, line in enumerate(pth_content.splitlines(), 1):
207 if line.startswith("#"):
208 continue
209 if line.strip() == "":
210 continue
211 try:
212 if line.startswith(("import ", "import\t")):
213 exec(line)
214 continue
215 line = line.rstrip()
216 dir, dircase = makepath(sitedir, line)
217 if dircase not in known_paths and os.path.exists(dir):
218 sys.path.append(dir)
219 known_paths.add(dircase)
220 except Exception as exc:
221 print(f"Error processing line {n:d} of {fullname}:\n",
222 file=sys.stderr)
223 import traceback
224 for record in traceback.format_exception(exc):
225 for line in record.splitlines():

Callers 1

addsitedirFunction · 0.85

Calls 15

_init_pathinfoFunction · 0.85
getattrFunction · 0.85
_traceFunction · 0.85
enumerateFunction · 0.85
makepathFunction · 0.85
lstatMethod · 0.80
execFunction · 0.50
printFunction · 0.50
joinMethod · 0.45
readMethod · 0.45
decodeMethod · 0.45
splitlinesMethod · 0.45

Tested by

no test coverage detected