Debian Codegraph @

lib-python/3/site.py

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