logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

site.py (22587B)


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