| 1 |
"""Append module search paths for third-party packages to sys.path. |
| 2 |
|
| 3 |
**************************************************************** |
| 4 |
* This module is automatically imported during initialization. * |
| 5 |
**************************************************************** |
| 6 |
|
| 7 |
This will append site-specific paths to the module search path. On |
| 8 |
Unix (including Mac OSX), it starts with sys.prefix and |
| •9 |
sys.exec_prefix (if different) and appends dist-packages. |
| 10 |
On other platforms (such as Windows), it tries each of the |
| 11 |
prefixes directly, as well as with lib/site-packages appended. The |
| 12 |
resulting directories, if they exist, are appended to sys.path, and |
| 13 |
also inspected for path configuration files. |
| 14 |
|
| •15 |
For Debian and derivatives, this sys.path is augmented with directories |
| 16 |
for packages distributed within the distribution. Local addons go |
| 17 |
into /usr/local/lib/pypy<version>/dist-packages, Debian addons |
| 18 |
install into /usr/lib/python3/dist-packages (which is shared with cPython). |
| 19 |
/usr/lib/pypy<version>/site-packages is not used. |
| 20 |
|
| 21 |
If a file named "pyvenv.cfg" exists one directory above sys.executable, |
| 22 |
sys.prefix and sys.exec_prefix are set to that directory and |
| 23 |
it is also checked for site-packages (sys.base_prefix and |
| 24 |
sys.base_exec_prefix will always be the "real" prefixes of the Python |
| 25 |
installation). If "pyvenv.cfg" (a bootstrap configuration file) contains |
| 26 |
the key "include-system-site-packages" set to anything other than "false" |
| 27 |
(case-insensitive), the system-level prefixes will still also be |
| 28 |
searched for site-packages; otherwise they won't. |
| 29 |
|
| 30 |
All of the resulting site-specific directories, if they exist, are |
| 31 |
appended to sys.path, and also inspected for path configuration |
| 32 |
files. |
| 33 |
|
| 34 |
A path configuration file is a file whose name has the form |
| 35 |
<package>.pth; its contents are additional directories (one per line) |
| 36 |
to be added to sys.path. Non-existing directories (or |
| 37 |
non-directories) are never added to sys.path; no directory is added to |
| 38 |
sys.path more than once. Blank lines and lines beginning with |
| 39 |
'#' are skipped. Lines starting with 'import' are executed. |
| 40 |
|
| 41 |
For example, suppose sys.prefix and sys.exec_prefix are set to |
| 42 |
/usr/local and there is a directory /usr/local/lib/python2.5/site-packages |
| 43 |
with three subdirectories, foo, bar and spam, and two path |
| 44 |
configuration files, foo.pth and bar.pth. Assume foo.pth contains the |
| 45 |
following: |
| 46 |
|
| 47 |
# foo package configuration |
| 48 |
foo |
| 49 |
bar |
| 50 |
bletch |
| 51 |
|
| 52 |
and bar.pth contains: |
| 53 |
|
| 54 |
# bar package configuration |
| 55 |
bar |
| 56 |
|
| 57 |
Then the following directories are added to sys.path, in this order: |
| 58 |
|
| 59 |
/usr/local/lib/python2.5/site-packages/bar |
| 60 |
/usr/local/lib/python2.5/site-packages/foo |
| 61 |
|
| 62 |
Note that bletch is omitted because it doesn't exist; bar precedes foo |
| 63 |
because bar.pth comes alphabetically before foo.pth; and spam is |
| 64 |
omitted because it is not mentioned in either path configuration file. |
| 65 |
|
| 66 |
The readline module is also automatically configured to enable |
| 67 |
completion for systems that support it. This can be overridden in |
| 68 |
sitecustomize, usercustomize or PYTHONSTARTUP. Starting Python in |
| 69 |
isolated mode (-I) disables automatic readline configuration. |
| 70 |
|
| 71 |
After these operations, an attempt is made to import a module |
| 72 |
named sitecustomize, which can perform arbitrary additional |
| 73 |
site-specific customizations. If this import fails with an |
| 74 |
ImportError exception, it is silently ignored. |
| 75 |
""" |
| 76 |
|
| 77 |
import sys |
| 78 |
import os |
| 79 |
import builtins |
| 80 |
import _sitebuiltins |
| 81 |
import io |
| 82 |
import stat |
| 83 |
|
| 84 |
is_pypy = sys.implementation.name == 'pypy' |
| 85 |
|
| 86 |
|
| 87 |
PREFIXES = [sys.prefix, sys.exec_prefix] |
| 88 |
|
| 89 |
|
| 90 |
ENABLE_USER_SITE = None |
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
USER_SITE = None |
| 96 |
USER_BASE = None |
| 97 |
|
| 98 |
|
| 99 |
def _trace(message): |
| 100 |
if sys.flags.verbose: |
| 101 |
print(message, file=sys.stderr) |
| 102 |
|
| 103 |
|
| 104 |
def makepath(*paths): |
| 105 |
dir = os.path.join(*paths) |
| 106 |
try: |
| 107 |
dir = os.path.abspath(dir) |
| 108 |
except OSError: |
| 109 |
pass |
| 110 |
return dir, os.path.normcase(dir) |
| 111 |
|
| 112 |
|
| 113 |
def abs_paths(): |
| 114 |
"""Set all module __file__ and __cached__ attributes to an absolute path""" |
| 115 |
for m in set(sys.modules.values()): |
| 116 |
loader_module = None |
| 117 |
try: |
| 118 |
loader_module = m.__loader__.__module__ |
| 119 |
except AttributeError: |
| 120 |
try: |
| 121 |
loader_module = m.__spec__.loader.__module__ |
| 122 |
except AttributeError: |
| 123 |
pass |
| 124 |
if loader_module not in {'_frozen_importlib', '_frozen_importlib_external'}: |
| 125 |
continue |
| 126 |
try: |
| 127 |
m.__file__ = os.path.abspath(m.__file__) |
| 128 |
except (AttributeError, OSError, TypeError): |
| 129 |
pass |
| 130 |
try: |
| 131 |
m.__cached__ = os.path.abspath(m.__cached__) |
| 132 |
except (AttributeError, OSError, TypeError): |
| 133 |
pass |
| 134 |
|
| 135 |
|
| 136 |
def removeduppaths(): |
| 137 |
""" Remove duplicate entries from sys.path along with making them |
| 138 |
absolute""" |
| 139 |
|
| 140 |
|
| 141 |
L = [] |
| 142 |
known_paths = set() |
| 143 |
for dir in sys.path: |
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
dir, dircase = makepath(dir) |
| 148 |
if dircase not in known_paths: |
| 149 |
L.append(dir) |
| 150 |
known_paths.add(dircase) |
| 151 |
sys.path[:] = L |
| 152 |
return known_paths |
| 153 |
|
| 154 |
|
| 155 |
def _init_pathinfo(): |
| 156 |
"""Return a set containing all existing file system items from sys.path.""" |
| 157 |
d = set() |
| 158 |
for item in sys.path: |
| 159 |
try: |
| 160 |
if os.path.exists(item): |
| 161 |
_, itemcase = makepath(item) |
| 162 |
d.add(itemcase) |
| 163 |
except TypeError: |
| 164 |
continue |
| 165 |
return d |
| 166 |
|
| 167 |
|
| 168 |
def 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 |
|
| 190 |
|
| 191 |
f = io.TextIOWrapper(io.open_code(fullname), encoding="locale") |
| 192 |
except OSError: |
| 193 |
return |
| 194 |
with f: |
| 195 |
for n, line in enumerate(f): |
| 196 |
if line.startswith("#"): |
| 197 |
continue |
| 198 |
if line.strip() == "": |
| 199 |
continue |
| 200 |
try: |
| 201 |
if line.startswith(("import ", "import\t")): |
| 202 |
exec(line) |
| 203 |
continue |
| 204 |
line = line.rstrip() |
| 205 |
dir, dircase = makepath(sitedir, line) |
| 206 |
if not dircase in known_paths and os.path.exists(dir): |
| 207 |
sys.path.append(dir) |
| 208 |
known_paths.add(dircase) |
| 209 |
except Exception: |
| 210 |
print("Error processing line {:d} of {}:\n".format(n+1, fullname), |
| 211 |
file=sys.stderr) |
| 212 |
import traceback |
| 213 |
for record in traceback.format_exception(*sys.exc_info()): |
| 214 |
for line in record.splitlines(): |
| 215 |
print(' '+line, file=sys.stderr) |
| 216 |
print("\nRemainder of file ignored", file=sys.stderr) |
| 217 |
break |
| 218 |
if reset: |
| 219 |
known_paths = None |
| 220 |
return known_paths |
| 221 |
|
| 222 |
|
| 223 |
def addsitedir(sitedir, known_paths=None): |
| 224 |
"""Add 'sitedir' argument to sys.path if missing and handle .pth files in |
| 225 |
'sitedir'""" |
| 226 |
_trace(f"Adding directory: {sitedir!r}") |
| 227 |
if known_paths is None: |
| 228 |
known_paths = _init_pathinfo() |
| 229 |
reset = True |
| 230 |
else: |
| 231 |
reset = False |
| 232 |
sitedir, sitedircase = makepath(sitedir) |
| 233 |
if not sitedircase in known_paths: |
| 234 |
sys.path.append(sitedir) |
| 235 |
known_paths.add(sitedircase) |
| 236 |
try: |
| 237 |
names = os.listdir(sitedir) |
| 238 |
except OSError: |
| 239 |
return |
| 240 |
names = [name for name in names |
| 241 |
if name.endswith(".pth") and not name.startswith(".")] |
| 242 |
for name in sorted(names): |
| 243 |
addpackage(sitedir, name, known_paths) |
| 244 |
if reset: |
| 245 |
known_paths = None |
| 246 |
return known_paths |
| 247 |
|
| 248 |
|
| 249 |
def check_enableusersite(): |
| 250 |
"""Check if user site directory is safe for inclusion |
| 251 |
|
| 252 |
The function tests for the command line flag (including environment var), |
| 253 |
process uid/gid equal to effective uid/gid. |
| 254 |
|
| 255 |
None: Disabled for security reasons |
| 256 |
False: Disabled by user (command line option) |
| 257 |
True: Safe and enabled |
| 258 |
""" |
| 259 |
if sys.flags.no_user_site: |
| 260 |
return False |
| 261 |
|
| 262 |
if hasattr(os, "getuid") and hasattr(os, "geteuid"): |
| 263 |
|
| 264 |
if os.geteuid() != os.getuid(): |
| 265 |
return None |
| 266 |
if hasattr(os, "getgid") and hasattr(os, "getegid"): |
| 267 |
|
| 268 |
if os.getegid() != os.getgid(): |
| 269 |
return None |
| 270 |
|
| 271 |
return True |
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
def _get_implementation(): |
| 282 |
if is_pypy: |
| 283 |
return 'PyPy' |
| 284 |
return 'Python' |
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
def _getuserbase(): |
| 289 |
env_base = os.environ.get("PYTHONUSERBASE", None) |
| 290 |
if env_base: |
| 291 |
return env_base |
| 292 |
|
| 293 |
|
| 294 |
if sys.platform in {"emscripten", "vxworks", "wasi"}: |
| 295 |
return None |
| 296 |
|
| 297 |
def joinuser(*args): |
| 298 |
return os.path.expanduser(os.path.join(*args)) |
| 299 |
|
| 300 |
if os.name == "nt": |
| 301 |
base = os.environ.get("APPDATA") or "~" |
| 302 |
return joinuser(base, _get_implementation()) |
| 303 |
|
| 304 |
if sys.platform == "darwin" and sys._framework: |
| 305 |
return joinuser("~", "Library", sys._framework, |
| 306 |
"%d.%d" % sys.version_info[:2]) |
| 307 |
|
| 308 |
return joinuser("~", ".local") |
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
def _get_path(userbase): |
| 313 |
version = sys.version_info |
| 314 |
|
| 315 |
implementation = _get_implementation() |
| 316 |
implementation_lower = implementation.lower() |
| 317 |
if os.name == 'nt': |
| 318 |
ver_nodot = sys.winver.replace('.', '') |
| 319 |
return f'{userbase}\\{implementation}{ver_nodot}\\site-packages' |
| 320 |
|
| 321 |
if sys.platform == 'darwin' and sys._framework: |
| 322 |
return f'{userbase}/lib/{implementation_lower}/site-packages' |
| 323 |
|
| 324 |
return f'{userbase}/lib/{implementation_lower}{version[0]}.{version[1]}/site-packages' |
| 325 |
|
| 326 |
|
| 327 |
def getuserbase(): |
| 328 |
"""Returns the `user base` directory path. |
| 329 |
|
| 330 |
The `user base` directory can be used to store data. If the global |
| 331 |
variable ``USER_BASE`` is not initialized yet, this function will also set |
| 332 |
it. |
| 333 |
""" |
| 334 |
global USER_BASE |
| 335 |
if USER_BASE is None: |
| 336 |
USER_BASE = _getuserbase() |
| 337 |
return USER_BASE |
| 338 |
|
| 339 |
|
| 340 |
def getusersitepackages(): |
| 341 |
"""Returns the user-specific site-packages directory path. |
| 342 |
|
| 343 |
If the global variable ``USER_SITE`` is not initialized yet, this |
| 344 |
function will also set it. |
| 345 |
""" |
| 346 |
global USER_SITE, ENABLE_USER_SITE |
| 347 |
userbase = getuserbase() |
| 348 |
|
| 349 |
if USER_SITE is None: |
| 350 |
if userbase is None: |
| 351 |
ENABLE_USER_SITE = False |
| 352 |
else: |
| 353 |
USER_SITE = _get_path(userbase) |
| 354 |
|
| 355 |
return USER_SITE |
| 356 |
|
| 357 |
def addusersitepackages(known_paths): |
| 358 |
"""Add a per user site-package to sys.path |
| 359 |
|
| 360 |
Each user has its own python directory with site-packages in the |
| 361 |
home directory. |
| 362 |
""" |
| 363 |
|
| 364 |
|
| 365 |
_trace("Processing user site-packages") |
| 366 |
user_site = getusersitepackages() |
| 367 |
|
| 368 |
if ENABLE_USER_SITE and os.path.isdir(user_site): |
| 369 |
addsitedir(user_site, known_paths) |
| 370 |
return known_paths |
| 371 |
|
| 372 |
def getsitepackages(prefixes=None): |
| 373 |
"""Returns a list containing all global site-packages directories. |
| 374 |
|
| 375 |
For each directory present in ``prefixes`` (or the global ``PREFIXES``), |
| 376 |
this function will find its `site-packages` subdirectory depending on the |
| 377 |
system environment, and will return a list of full paths. |
| 378 |
""" |
| 379 |
sitepackages = [] |
| 380 |
seen = set() |
| 381 |
|
| 382 |
if prefixes is None: |
| 383 |
prefixes = PREFIXES |
| 384 |
|
| •385 |
is_virtual_environment = sys.base_prefix != sys.prefix or hasattr(sys, "real_prefix") |
| 386 |
|
| 387 |
for prefix in prefixes: |
| 388 |
if not prefix or prefix in seen: |
| 389 |
continue |
| 390 |
seen.add(prefix) |
| 391 |
|
| 392 |
implementation = _get_implementation().lower() |
| 393 |
if os.sep == '/': |
| 394 |
libdirs = [sys.platlibdir] |
| 395 |
if sys.platlibdir != "lib": |
| 396 |
libdirs.append("lib") |
| 397 |
|
| •398 |
if is_virtual_environment: |
| 399 |
sitepackages.append(os.path.join( |
| 400 |
prefix, "lib", |
| 401 |
f"{implementation}%d.%d" % sys.version_info[:2], |
| 402 |
"site-packages")) |
| 403 |
sitepackages.append(os.path.join( |
| 404 |
prefix, "local", "lib", |
| 405 |
f"{implementation}%d.%d" % sys.version_info[:2], |
| 406 |
"dist-packages")) |
| 407 |
sitepackages.append(os.path.join( |
| 408 |
prefix, "lib", "python3", "dist-packages")) |
| 409 |
else: |
| 410 |
sitepackages.append(prefix) |
| 411 |
sitepackages.append(os.path.join(prefix, "Lib", "site-packages")) |
| 412 |
return sitepackages |
| 413 |
|
| 414 |
def addsitepackages(known_paths, prefixes=None): |
| 415 |
"""Add site-packages to sys.path""" |
| 416 |
_trace("Processing global site-packages") |
| 417 |
for sitedir in getsitepackages(prefixes): |
| 418 |
if os.path.isdir(sitedir): |
| 419 |
addsitedir(sitedir, known_paths) |
| 420 |
|
| 421 |
return known_paths |
| 422 |
|
| 423 |
def setquit(): |
| 424 |
"""Define new builtins 'quit' and 'exit'. |
| 425 |
|
| 426 |
These are objects which make the interpreter exit when called. |
| 427 |
The repr of each object contains a hint at how it works. |
| 428 |
|
| 429 |
""" |
| 430 |
if os.sep == '\\': |
| 431 |
eof = 'Ctrl-Z plus Return' |
| 432 |
else: |
| 433 |
eof = 'Ctrl-D (i.e. EOF)' |
| 434 |
|
| 435 |
builtins.quit = _sitebuiltins.Quitter('quit', eof) |
| 436 |
builtins.exit = _sitebuiltins.Quitter('exit', eof) |
| 437 |
|
| 438 |
|
| 439 |
def setcopyright(): |
| 440 |
"""Set 'copyright' and 'credits' in builtins""" |
| 441 |
builtins.copyright = _sitebuiltins._Printer("copyright", sys.copyright) |
| 442 |
licenseargs = None |
| 443 |
if is_pypy: |
| 444 |
builtins.credits = _sitebuiltins._Printer( |
| 445 |
"credits", |
| 446 |
"PyPy is maintained by the PyPy developers.\n" |
| 447 |
"For more information see: https://pypy.org/") |
| 448 |
builtins.license = _sitebuiltins._Printer( |
| 449 |
"license", |
| 450 |
"See https://foss.heptapod.net/pypy/pypy/src/default/LICENSE") |
| 451 |
elif sys.platform[:4] == 'java': |
| 452 |
builtins.credits = _sitebuiltins._Printer( |
| 453 |
"credits", |
| 454 |
"Jython is maintained by the Jython developers (www.jython.org).") |
| 455 |
else: |
| 456 |
builtins.credits = _sitebuiltins._Printer("credits", """\ |
| 457 |
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands |
| 458 |
for supporting Python development. See www.python.org for more information.""") |
| 459 |
files, dirs = [], [] |
| 460 |
|
| 461 |
|
| 462 |
here = getattr(sys, '_stdlib_dir', None) |
| 463 |
if not here and hasattr(os, '__file__'): |
| 464 |
here = os.path.dirname(os.__file__) |
| 465 |
if here: |
| 466 |
files.extend(["LICENSE.txt", "LICENSE"]) |
| 467 |
dirs.extend([os.path.join(here, os.pardir), here, os.curdir]) |
| 468 |
builtins.license = _sitebuiltins._Printer( |
| 469 |
"license", |
| 470 |
"See https://www.python.org/psf/license/", |
| 471 |
files, dirs) |
| 472 |
|
| 473 |
|
| 474 |
def sethelper(): |
| 475 |
builtins.help = _sitebuiltins._Helper() |
| 476 |
|
| 477 |
|
| 478 |
def gethistoryfile(): |
| 479 |
"""Check if the PYTHON_HISTORY environment variable is set and define |
| 480 |
it as the .python_history file. If PYTHON_HISTORY is not set, use the |
| 481 |
default .python_history file. |
| 482 |
""" |
| 483 |
|
| 484 |
if not sys.flags.ignore_environment: |
| 485 |
history = os.environ.get("PYTHON_HISTORY") |
| 486 |
if history: |
| 487 |
return history |
| 488 |
return os.path.join(os.path.expanduser('~'), |
| 489 |
'.python_history') |
| 490 |
|
| 491 |
|
| 492 |
def enablerlcompleter(): |
| 493 |
"""Enable default readline configuration on interactive prompts, by |
| 494 |
registering a sys.__interactivehook__. |
| 495 |
""" |
| 496 |
sys.__interactivehook__ = register_readline |
| 497 |
|
| 498 |
|
| 499 |
def register_readline(): |
| 500 |
"""Configure readline completion on interactive prompts. |
| 501 |
|
| 502 |
If the readline module can be imported, the hook will set the Tab key |
| 503 |
as completion key and register ~/.python_history as history file. |
| 504 |
This can be overridden in the sitecustomize or usercustomize module, |
| 505 |
or in a PYTHONSTARTUP file. |
| 506 |
""" |
| 507 |
if not sys.flags.ignore_environment: |
| 508 |
PYTHON_BASIC_REPL = os.getenv("PYTHON_BASIC_REPL") |
| 509 |
else: |
| 510 |
PYTHON_BASIC_REPL = False |
| 511 |
|
| 512 |
import atexit |
| 513 |
|
| 514 |
try: |
| 515 |
try: |
| 516 |
import pyrepl.readline as readline |
| 517 |
except ImportError: |
| 518 |
readline = None |
| 519 |
else: |
| 520 |
import rlcompleter |
| 521 |
except ImportError: |
| 522 |
return |
| 523 |
|
| 524 |
try: |
| 525 |
if PYTHON_BASIC_REPL: |
| 526 |
CAN_USE_PYREPL = False |
| 527 |
else: |
| 528 |
original_path = sys.path |
| 529 |
sys.path = [p for p in original_path if p != ''] |
| 530 |
try: |
| 531 |
import pyrepl.readline |
| 532 |
if os.name == "nt": |
| 533 |
import pyrepl.windows_console |
| 534 |
console_errors = (pyrepl.windows_console._error,) |
| 535 |
else: |
| 536 |
import pyrepl.unix_console |
| 537 |
console_errors = pyrepl.unix_console._error |
| 538 |
from pyrepl.main import CAN_USE_PYREPL |
| 539 |
finally: |
| 540 |
sys.path = original_path |
| 541 |
except ImportError: |
| 542 |
return |
| 543 |
|
| 544 |
if readline is not None: |
| 545 |
|
| 546 |
|
| 547 |
if 0 and readline.backend == 'editline': |
| 548 |
readline.parse_and_bind('bind ^I rl_complete') |
| 549 |
else: |
| 550 |
readline.parse_and_bind('tab: complete') |
| 551 |
|
| 552 |
try: |
| 553 |
if not is_pypy: |
| 554 |
readline.read_init_file() |
| 555 |
except OSError: |
| 556 |
|
| 557 |
|
| 558 |
|
| 559 |
|
| 560 |
pass |
| 561 |
|
| 562 |
if readline is None or readline.get_current_history_length() == 0: |
| 563 |
|
| 564 |
|
| 565 |
|
| 566 |
|
| 567 |
|
| 568 |
|
| 569 |
history = gethistoryfile() |
| 570 |
|
| 571 |
if CAN_USE_PYREPL: |
| 572 |
readline_module = pyrepl.readline |
| 573 |
exceptions = (OSError, *console_errors) |
| 574 |
else: |
| 575 |
if readline is None: |
| 576 |
return |
| 577 |
readline_module = readline |
| 578 |
exceptions = OSError |
| 579 |
|
| 580 |
try: |
| 581 |
readline_module.read_history_file(history) |
| 582 |
except exceptions: |
| 583 |
pass |
| 584 |
|
| 585 |
def write_history(): |
| 586 |
try: |
| 587 |
readline_module.write_history_file(history) |
| 588 |
except (FileNotFoundError, PermissionError): |
| 589 |
|
| 590 |
|
| 591 |
pass |
| 592 |
|
| 593 |
atexit.register(write_history) |
| 594 |
|
| 595 |
|
| 596 |
def venv(known_paths): |
| 597 |
global PREFIXES, ENABLE_USER_SITE |
| 598 |
|
| 599 |
env = os.environ |
| 600 |
if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in env: |
| 601 |
executable = sys._base_executable = os.environ['__PYVENV_LAUNCHER__'] |
| 602 |
else: |
| 603 |
executable = sys.executable |
| 604 |
exe_dir, _ = os.path.split(os.path.abspath(executable)) |
| 605 |
site_prefix = os.path.dirname(exe_dir) |
| 606 |
sys._home = None |
| 607 |
conf_basename = 'pyvenv.cfg' |
| 608 |
candidate_confs = [ |
| 609 |
conffile for conffile in ( |
| 610 |
os.path.join(exe_dir, conf_basename), |
| 611 |
os.path.join(site_prefix, conf_basename) |
| 612 |
) |
| 613 |
if os.path.isfile(conffile) |
| 614 |
] |
| 615 |
|
| 616 |
if candidate_confs: |
| 617 |
virtual_conf = candidate_confs[0] |
| 618 |
system_site = "true" |
| 619 |
|
| 620 |
|
| 621 |
with open(virtual_conf, encoding='utf-8') as f: |
| 622 |
for line in f: |
| 623 |
if '=' in line: |
| 624 |
key, _, value = line.partition('=') |
| 625 |
key = key.strip().lower() |
| 626 |
value = value.strip() |
| 627 |
if key == 'include-system-site-packages': |
| 628 |
system_site = value.lower() |
| 629 |
elif key == 'home': |
| 630 |
sys._home = value |
| 631 |
|
| 632 |
sys.prefix = sys.exec_prefix = site_prefix |
| 633 |
|
| 634 |
|
| 635 |
addsitepackages(known_paths, [sys.prefix]) |
| 636 |
|
| 637 |
|
| 638 |
|
| 639 |
if system_site == "true": |
| 640 |
PREFIXES.insert(0, sys.prefix) |
| 641 |
else: |
| 642 |
PREFIXES = [sys.prefix] |
| 643 |
ENABLE_USER_SITE = False |
| 644 |
|
| 645 |
return known_paths |
| 646 |
|
| 647 |
|
| 648 |
def execsitecustomize(): |
| 649 |
"""Run custom site specific code, if available.""" |
| 650 |
try: |
| 651 |
try: |
| 652 |
import sitecustomize |
| 653 |
except ImportError as exc: |
| 654 |
if exc.name == 'sitecustomize': |
| 655 |
pass |
| 656 |
else: |
| 657 |
raise |
| 658 |
except Exception as err: |
| 659 |
if sys.flags.verbose: |
| 660 |
sys.excepthook(*sys.exc_info()) |
| 661 |
else: |
| 662 |
sys.stderr.write( |
| 663 |
"Error in sitecustomize; set PYTHONVERBOSE for traceback:\n" |
| 664 |
"%s: %s\n" % |
| 665 |
(err.__class__.__name__, err)) |
| 666 |
|
| 667 |
|
| 668 |
def execusercustomize(): |
| 669 |
"""Run custom user specific code, if available.""" |
| 670 |
try: |
| 671 |
try: |
| 672 |
import usercustomize |
| 673 |
except ImportError as exc: |
| 674 |
if exc.name == 'usercustomize': |
| 675 |
pass |
| 676 |
else: |
| 677 |
raise |
| 678 |
except Exception as err: |
| 679 |
if sys.flags.verbose: |
| 680 |
sys.excepthook(*sys.exc_info()) |
| 681 |
else: |
| 682 |
sys.stderr.write( |
| 683 |
"Error in usercustomize; set PYTHONVERBOSE for traceback:\n" |
| 684 |
"%s: %s\n" % |
| 685 |
(err.__class__.__name__, err)) |
| 686 |
|
| 687 |
|
| 688 |
def main(): |
| 689 |
"""Add standard site-specific directories to the module search path. |
| 690 |
|
| 691 |
This function is called automatically when this module is imported, |
| 692 |
unless the python interpreter was started with the -S flag. |
| 693 |
""" |
| 694 |
global ENABLE_USER_SITE |
| 695 |
|
| 696 |
orig_path = sys.path[:] |
| 697 |
known_paths = removeduppaths() |
| 698 |
if orig_path != sys.path: |
| 699 |
|
| 700 |
|
| 701 |
abs_paths() |
| 702 |
|
| 703 |
known_paths = venv(known_paths) |
| 704 |
if ENABLE_USER_SITE is None: |
| 705 |
ENABLE_USER_SITE = check_enableusersite() |
| 706 |
known_paths = addusersitepackages(known_paths) |
| 707 |
known_paths = addsitepackages(known_paths) |
| 708 |
setquit() |
| 709 |
setcopyright() |
| 710 |
sethelper() |
| 711 |
if not sys.flags.isolated: |
| 712 |
enablerlcompleter() |
| 713 |
execsitecustomize() |
| 714 |
if ENABLE_USER_SITE: |
| 715 |
execusercustomize() |
| 716 |
|
| 717 |
|
| 718 |
|
| 719 |
if not sys.flags.no_site: |
| 720 |
main() |
| 721 |
|
| 722 |
def _script(): |
| 723 |
help = """\ |
| 724 |
%s [--user-base] [--user-site] |
| 725 |
|
| 726 |
Without arguments print some useful information |
| 727 |
With arguments print the value of USER_BASE and/or USER_SITE separated |
| 728 |
by '%s'. |
| 729 |
|
| 730 |
Exit codes with --user-base or --user-site: |
| 731 |
0 - user site directory is enabled |
| 732 |
1 - user site directory is disabled by user |
| 733 |
2 - user site directory is disabled by super user |
| 734 |
or for security reasons |
| 735 |
>2 - unknown error |
| 736 |
""" |
| 737 |
args = sys.argv[1:] |
| 738 |
if not args: |
| 739 |
user_base = getuserbase() |
| 740 |
user_site = getusersitepackages() |
| 741 |
print("sys.path = [") |
| 742 |
for dir in sys.path: |
| 743 |
print(" %r," % (dir,)) |
| 744 |
print("]") |
| 745 |
def exists(path): |
| 746 |
if path is not None and os.path.isdir(path): |
| 747 |
return "exists" |
| 748 |
else: |
| 749 |
return "doesn't exist" |
| 750 |
print(f"USER_BASE: {user_base!r} ({exists(user_base)})") |
| 751 |
print(f"USER_SITE: {user_site!r} ({exists(user_site)})") |
| 752 |
print(f"ENABLE_USER_SITE: {ENABLE_USER_SITE!r}") |
| 753 |
sys.exit(0) |
| 754 |
|
| 755 |
buffer = [] |
| 756 |
if '--user-base' in args: |
| 757 |
buffer.append(USER_BASE) |
| 758 |
if '--user-site' in args: |
| 759 |
buffer.append(USER_SITE) |
| 760 |
|
| 761 |
if buffer: |
| 762 |
print(os.pathsep.join(buffer)) |
| 763 |
if ENABLE_USER_SITE: |
| 764 |
sys.exit(0) |
| 765 |
elif ENABLE_USER_SITE is False: |
| 766 |
sys.exit(1) |
| 767 |
elif ENABLE_USER_SITE is None: |
| 768 |
sys.exit(2) |
| 769 |
else: |
| 770 |
sys.exit(3) |
| 771 |
else: |
| 772 |
import textwrap |
| 773 |
print(textwrap.dedent(help % (sys.argv[0], os.pathsep))) |
| 774 |
sys.exit(10) |
| 775 |
|
| 776 |
if __name__ == '__main__': |
| 777 |
_script() |