blob: 5f1b31e73d90ad68330472529e0f415456fd7de2 [file] [log] [blame]
Guido van Rossumf30bec71997-08-29 22:30:45 +00001"""Append module search paths for third-party packages to sys.path.
Guido van Rossume57c96e1996-08-17 19:56:26 +00002
Guido van Rossumf30bec71997-08-29 22:30:45 +00003****************************************************************
4* This module is automatically imported during initialization. *
5****************************************************************
Guido van Rossume57c96e1996-08-17 19:56:26 +00006
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00007This will append site-specific paths to the module search path. On
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008Unix (including Mac OSX), it starts with sys.prefix and
9sys.exec_prefix (if different) and appends
Antoine Pitrou9e82b172014-06-12 19:41:30 -040010lib/python<version>/site-packages.
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011On other platforms (such as Windows), it tries each of the
12prefixes directly, as well as with lib/site-packages appended. The
Guido van Rossum62b297b1997-09-08 02:14:09 +000013resulting directories, if they exist, are appended to sys.path, and
14also inspected for path configuration files.
Guido van Rossume57c96e1996-08-17 19:56:26 +000015
Vinay Sajip7ded1f02012-05-26 03:45:29 +010016If a file named "pyvenv.cfg" exists one directory above sys.executable,
17sys.prefix and sys.exec_prefix are set to that directory and
Antoine Pitrou9e82b172014-06-12 19:41:30 -040018it is also checked for site-packages (sys.base_prefix and
Vinay Sajipabd344c2012-07-03 16:33:57 +010019sys.base_exec_prefix will always be the "real" prefixes of the Python
Vinay Sajip7ded1f02012-05-26 03:45:29 +010020installation). If "pyvenv.cfg" (a bootstrap configuration file) contains
21the key "include-system-site-packages" set to anything other than "false"
22(case-insensitive), the system-level prefixes will still also be
23searched for site-packages; otherwise they won't.
24
25All of the resulting site-specific directories, if they exist, are
26appended to sys.path, and also inspected for path configuration
27files.
28
Guido van Rossumf30bec71997-08-29 22:30:45 +000029A path configuration file is a file whose name has the form
30<package>.pth; its contents are additional directories (one per line)
31to be added to sys.path. Non-existing directories (or
32non-directories) are never added to sys.path; no directory is added to
33sys.path more than once. Blank lines and lines beginning with
Guido van Rossumfacf24b2001-12-17 16:07:06 +000034'#' are skipped. Lines starting with 'import' are executed.
Guido van Rossume57c96e1996-08-17 19:56:26 +000035
Guido van Rossumf30bec71997-08-29 22:30:45 +000036For example, suppose sys.prefix and sys.exec_prefix are set to
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000037/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
Guido van Rossum62b297b1997-09-08 02:14:09 +000038with three subdirectories, foo, bar and spam, and two path
39configuration files, foo.pth and bar.pth. Assume foo.pth contains the
40following:
Guido van Rossumf30bec71997-08-29 22:30:45 +000041
42 # foo package configuration
43 foo
44 bar
45 bletch
46
47and bar.pth contains:
48
49 # bar package configuration
50 bar
51
52Then the following directories are added to sys.path, in this order:
53
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000054 /usr/local/lib/python2.5/site-packages/bar
55 /usr/local/lib/python2.5/site-packages/foo
Guido van Rossumf30bec71997-08-29 22:30:45 +000056
57Note that bletch is omitted because it doesn't exist; bar precedes foo
58because bar.pth comes alphabetically before foo.pth; and spam is
59omitted because it is not mentioned in either path configuration file.
Guido van Rossume57c96e1996-08-17 19:56:26 +000060
Antoine Pitrou1a6cb302013-05-04 20:08:35 +020061The readline module is also automatically configured to enable
Martin Pantere26da7c2016-06-02 10:07:09 +000062completion for systems that support it. This can be overridden in
Steve Dower313523c2016-09-17 12:22:41 -070063sitecustomize, usercustomize or PYTHONSTARTUP. Starting Python in
64isolated mode (-I) disables automatic readline configuration.
Antoine Pitrou1a6cb302013-05-04 20:08:35 +020065
66After these operations, an attempt is made to import a module
Guido van Rossumf30bec71997-08-29 22:30:45 +000067named sitecustomize, which can perform arbitrary additional
68site-specific customizations. If this import fails with an
69ImportError exception, it is silently ignored.
Guido van Rossume57c96e1996-08-17 19:56:26 +000070"""
71
Brett Cannon0096e262004-06-05 01:12:51 +000072import sys
73import os
Georg Brandl1a3284e2007-12-02 09:40:06 +000074import builtins
Antoine Pitrou853395b2013-08-06 22:56:40 +020075import _sitebuiltins
Steve Dower184f3d42019-06-21 15:16:46 -070076import io
Guido van Rossume57c96e1996-08-17 19:56:26 +000077
Christian Heimes8dc226f2008-05-06 23:45:46 +000078# Prefixes for site-packages; add additional prefixes like /usr/local here
79PREFIXES = [sys.prefix, sys.exec_prefix]
80# Enable per user site-packages directory
81# set it to False to disable the feature or True to force the feature
82ENABLE_USER_SITE = None
Tarek Ziadé4a608c02009-08-20 21:28:05 +000083
Christian Heimes8dc226f2008-05-06 23:45:46 +000084# for distutils.commands.install
Tarek Ziadé4a608c02009-08-20 21:28:05 +000085# These values are initialized by the getuserbase() and getusersitepackages()
86# functions, through the main() function when Python starts.
Christian Heimes8dc226f2008-05-06 23:45:46 +000087USER_SITE = None
88USER_BASE = None
89
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000090
native-api2145c8c2020-06-12 09:20:11 +030091def _trace(message):
92 if sys.flags.verbose:
93 print(message, file=sys.stderr)
94
95
Fred Drake38cb9f12000-09-28 16:52:36 +000096def makepath(*paths):
Victor Stinnerb103a932010-10-12 22:23:23 +000097 dir = os.path.join(*paths)
98 try:
99 dir = os.path.abspath(dir)
100 except OSError:
101 pass
Fred Drake1fb5ce02001-07-02 16:55:42 +0000102 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +0000103
Christian Heimes8dc226f2008-05-06 23:45:46 +0000104
Barry Warsaw28a691b2010-04-17 00:19:56 +0000105def abs_paths():
106 """Set all module __file__ and __cached__ attributes to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +0000107 for m in set(sys.modules.values()):
Brett Cannon825ac382020-11-06 18:45:56 -0800108 loader_module = None
109 try:
110 loader_module = m.__loader__.__module__
111 except AttributeError:
112 try:
113 loader_module = m.__spec__.loader.__module__
114 except AttributeError:
115 pass
116 if loader_module not in {'_frozen_importlib', '_frozen_importlib_external'}:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000117 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +0000118 try:
119 m.__file__ = os.path.abspath(m.__file__)
Steve Weber2487f302018-06-10 20:49:34 -0400120 except (AttributeError, OSError, TypeError):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000121 pass
122 try:
123 m.__cached__ = os.path.abspath(m.__cached__)
Steve Weber2487f302018-06-10 20:49:34 -0400124 except (AttributeError, OSError, TypeError):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000125 pass
Fred Drake38cb9f12000-09-28 16:52:36 +0000126
Christian Heimes8dc226f2008-05-06 23:45:46 +0000127
Brett Cannon0096e262004-06-05 01:12:51 +0000128def removeduppaths():
129 """ Remove duplicate entries from sys.path along with making them
130 absolute"""
131 # This ensures that the initial path provided by the interpreter contains
132 # only absolute pathnames, even if we're running from the build directory.
133 L = []
134 known_paths = set()
135 for dir in sys.path:
136 # Filter out duplicate paths (on case-insensitive file systems also
137 # if they only differ in case); turn relative paths into absolute
138 # paths.
139 dir, dircase = makepath(dir)
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900140 if dircase not in known_paths:
Brett Cannon0096e262004-06-05 01:12:51 +0000141 L.append(dir)
142 known_paths.add(dircase)
143 sys.path[:] = L
144 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000145
Christian Heimes8dc226f2008-05-06 23:45:46 +0000146
Fred Drake7f5296e2001-07-20 20:06:17 +0000147def _init_pathinfo():
Brett Cannon5f0507d2016-04-08 15:04:28 -0700148 """Return a set containing all existing file system items from sys.path."""
Brett Cannon0096e262004-06-05 01:12:51 +0000149 d = set()
Brett Cannon5f0507d2016-04-08 15:04:28 -0700150 for item in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000151 try:
Brett Cannon5f0507d2016-04-08 15:04:28 -0700152 if os.path.exists(item):
153 _, itemcase = makepath(item)
154 d.add(itemcase)
Brett Cannon0096e262004-06-05 01:12:51 +0000155 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000156 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000157 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000158
Christian Heimes8dc226f2008-05-06 23:45:46 +0000159
Brett Cannon0096e262004-06-05 01:12:51 +0000160def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000161 """Process a .pth file within the site-packages directory:
162 For each line in the file, either combine it with sitedir to a path
163 and add that to known_paths, or execute it if it starts with 'import '.
164 """
Brett Cannon0096e262004-06-05 01:12:51 +0000165 if known_paths is None:
Brett Cannon13252b82013-01-25 13:57:16 -0500166 known_paths = _init_pathinfo()
Brett Cannon5f0507d2016-04-08 15:04:28 -0700167 reset = True
Fred Drake7f5296e2001-07-20 20:06:17 +0000168 else:
Brett Cannon5f0507d2016-04-08 15:04:28 -0700169 reset = False
Brett Cannon0096e262004-06-05 01:12:51 +0000170 fullname = os.path.join(sitedir, name)
native-api2145c8c2020-06-12 09:20:11 +0300171 _trace(f"Processing .pth file: {fullname!r}")
Brett Cannon0096e262004-06-05 01:12:51 +0000172 try:
Steve Dower184f3d42019-06-21 15:16:46 -0700173 f = io.TextIOWrapper(io.open_code(fullname))
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200174 except OSError:
Brett Cannon0096e262004-06-05 01:12:51 +0000175 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000176 with f:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000177 for n, line in enumerate(f):
Brett Cannon0096e262004-06-05 01:12:51 +0000178 if line.startswith("#"):
179 continue
idomic0c71a662020-09-19 15:13:29 -0400180 if line.strip() == "":
181 continue
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000182 try:
183 if line.startswith(("import ", "import\t")):
184 exec(line)
185 continue
186 line = line.rstrip()
187 dir, dircase = makepath(sitedir, line)
188 if not dircase in known_paths and os.path.exists(dir):
189 sys.path.append(dir)
190 known_paths.add(dircase)
Florent Xicluna54540ec2011-11-04 08:29:17 +0100191 except Exception:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000192 print("Error processing line {:d} of {}:\n".format(n+1, fullname),
193 file=sys.stderr)
Victor Stinner65532112012-02-21 22:10:16 +0100194 import traceback
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000195 for record in traceback.format_exception(*sys.exc_info()):
196 for line in record.splitlines():
197 print(' '+line, file=sys.stderr)
198 print("\nRemainder of file ignored", file=sys.stderr)
199 break
Brett Cannon0096e262004-06-05 01:12:51 +0000200 if reset:
201 known_paths = None
202 return known_paths
203
Christian Heimes8dc226f2008-05-06 23:45:46 +0000204
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000205def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000206 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
207 'sitedir'"""
native-api2145c8c2020-06-12 09:20:11 +0300208 _trace(f"Adding directory: {sitedir!r}")
Brett Cannon0096e262004-06-05 01:12:51 +0000209 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000210 known_paths = _init_pathinfo()
Brett Cannon5f0507d2016-04-08 15:04:28 -0700211 reset = True
Brett Cannon0096e262004-06-05 01:12:51 +0000212 else:
Brett Cannon5f0507d2016-04-08 15:04:28 -0700213 reset = False
Fred Drake1fb5ce02001-07-02 16:55:42 +0000214 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000215 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000216 sys.path.append(sitedir) # Add path component
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100217 known_paths.add(sitedircase)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000218 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000219 names = os.listdir(sitedir)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200220 except OSError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000222 names = [name for name in names if name.endswith(".pth")]
223 for name in sorted(names):
224 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000225 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000226 known_paths = None
227 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000228
Christian Heimes8dc226f2008-05-06 23:45:46 +0000229
230def check_enableusersite():
231 """Check if user site directory is safe for inclusion
232
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000233 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000234 process uid/gid equal to effective uid/gid.
235
236 None: Disabled for security reasons
237 False: Disabled by user (command line option)
238 True: Safe and enabled
239 """
240 if sys.flags.no_user_site:
241 return False
242
243 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
244 # check process uid == effective uid
245 if os.geteuid() != os.getuid():
246 return None
247 if hasattr(os, "getgid") and hasattr(os, "getegid"):
248 # check process gid == effective gid
249 if os.getegid() != os.getgid():
250 return None
251
252 return True
253
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900254
255# NOTE: sysconfig and it's dependencies are relatively large but site module
256# needs very limited part of them.
257# To speedup startup time, we have copy of them.
258#
259# See https://bugs.python.org/issue29585
260
261# Copy of sysconfig._getuserbase()
262def _getuserbase():
263 env_base = os.environ.get("PYTHONUSERBASE", None)
264 if env_base:
265 return env_base
266
pxinwrab74c012020-12-21 06:27:42 +0800267 # VxWorks has no home directories
268 if sys.platform == "vxworks":
269 return None
270
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900271 def joinuser(*args):
272 return os.path.expanduser(os.path.join(*args))
273
274 if os.name == "nt":
275 base = os.environ.get("APPDATA") or "~"
276 return joinuser(base, "Python")
277
278 if sys.platform == "darwin" and sys._framework:
279 return joinuser("~", "Library", sys._framework,
280 "%d.%d" % sys.version_info[:2])
281
282 return joinuser("~", ".local")
283
284
285# Same to sysconfig.get_path('purelib', os.name+'_user')
286def _get_path(userbase):
287 version = sys.version_info
288
289 if os.name == 'nt':
Steve Dowerdd180012020-09-05 00:45:54 +0100290 ver_nodot = sys.winver.replace('.', '')
291 return f'{userbase}\\Python{ver_nodot}\\site-packages'
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900292
293 if sys.platform == 'darwin' and sys._framework:
294 return f'{userbase}/lib/python/site-packages'
295
296 return f'{userbase}/lib/python{version[0]}.{version[1]}/site-packages'
297
298
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000299def getuserbase():
300 """Returns the `user base` directory path.
301
302 The `user base` directory can be used to store data. If the global
303 variable ``USER_BASE`` is not initialized yet, this function will also set
304 it.
305 """
306 global USER_BASE
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900307 if USER_BASE is None:
308 USER_BASE = _getuserbase()
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000309 return USER_BASE
310
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900311
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000312def getusersitepackages():
313 """Returns the user-specific site-packages directory path.
314
315 If the global variable ``USER_SITE`` is not initialized yet, this
316 function will also set it.
317 """
pxinwrab74c012020-12-21 06:27:42 +0800318 global USER_SITE, ENABLE_USER_SITE
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900319 userbase = getuserbase() # this will also set USER_BASE
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000320
INADA Naokia8f8d5b2017-06-29 00:31:53 +0900321 if USER_SITE is None:
pxinwrab74c012020-12-21 06:27:42 +0800322 if userbase is None:
323 ENABLE_USER_SITE = False # disable user site and return None
324 else:
325 USER_SITE = _get_path(userbase)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000326
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000327 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000328
329def addusersitepackages(known_paths):
330 """Add a per user site-package to sys.path
331
332 Each user has its own python directory with site-packages in the
333 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000334 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000335 # get the per user site-package path
336 # this call will also make sure USER_BASE and USER_SITE are set
native-api2145c8c2020-06-12 09:20:11 +0300337 _trace("Processing user site-packages")
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000338 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000339
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000340 if ENABLE_USER_SITE and os.path.isdir(user_site):
341 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000342 return known_paths
343
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100344def getsitepackages(prefixes=None):
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400345 """Returns a list containing all global site-packages directories.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000346
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100347 For each directory present in ``prefixes`` (or the global ``PREFIXES``),
348 this function will find its `site-packages` subdirectory depending on the
349 system environment, and will return a list of full paths.
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000350 """
351 sitepackages = []
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000352 seen = set()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000353
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100354 if prefixes is None:
355 prefixes = PREFIXES
356
357 for prefix in prefixes:
Christian Heimes8dc226f2008-05-06 23:45:46 +0000358 if not prefix or prefix in seen:
359 continue
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000360 seen.add(prefix)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000361
Victor Stinner8510f432020-03-10 09:53:09 +0100362 libdirs = [sys.platlibdir]
363 if sys.platlibdir != "lib":
364 libdirs.append("lib")
365
Christian Heimesde0b9622012-11-19 00:59:39 +0100366 if os.sep == '/':
Victor Stinner8510f432020-03-10 09:53:09 +0100367 for libdir in libdirs:
368 path = os.path.join(prefix, libdir,
369 "python%d.%d" % sys.version_info[:2],
370 "site-packages")
371 sitepackages.append(path)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000372 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000373 sitepackages.append(prefix)
Victor Stinner8510f432020-03-10 09:53:09 +0100374
375 for libdir in libdirs:
376 path = os.path.join(prefix, libdir, "site-packages")
377 sitepackages.append(path)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000378 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000379
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100380def addsitepackages(known_paths, prefixes=None):
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400381 """Add site-packages to sys.path"""
native-api2145c8c2020-06-12 09:20:11 +0300382 _trace("Processing global site-packages")
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100383 for sitedir in getsitepackages(prefixes):
Christian Heimes8dc226f2008-05-06 23:45:46 +0000384 if os.path.isdir(sitedir):
385 addsitedir(sitedir, known_paths)
386
387 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000388
Brett Cannon0096e262004-06-05 01:12:51 +0000389def setquit():
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000390 """Define new builtins 'quit' and 'exit'.
391
392 These are objects which make the interpreter exit when called.
393 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000394
Brett Cannon0096e262004-06-05 01:12:51 +0000395 """
Ned Deilyc6ef5032016-10-01 21:12:16 -0400396 if os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000397 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000398 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000399 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000400
Antoine Pitrou853395b2013-08-06 22:56:40 +0200401 builtins.quit = _sitebuiltins.Quitter('quit', eof)
402 builtins.exit = _sitebuiltins.Quitter('exit', eof)
Brett Cannon0096e262004-06-05 01:12:51 +0000403
404
Brett Cannon0096e262004-06-05 01:12:51 +0000405def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000406 """Set 'copyright' and 'credits' in builtins"""
Antoine Pitrou853395b2013-08-06 22:56:40 +0200407 builtins.copyright = _sitebuiltins._Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000408 if sys.platform[:4] == 'java':
Antoine Pitrou853395b2013-08-06 22:56:40 +0200409 builtins.credits = _sitebuiltins._Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000410 "credits",
Antoine Pitrouf93c7b82013-08-01 19:46:04 +0200411 "Jython is maintained by the Jython developers (www.jython.org).")
Brett Cannon0096e262004-06-05 01:12:51 +0000412 else:
Antoine Pitrou853395b2013-08-06 22:56:40 +0200413 builtins.credits = _sitebuiltins._Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000414 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
Antoine Pitrouf93c7b82013-08-01 19:46:04 +0200415 for supporting Python development. See www.python.org for more information.""")
Martin v. Löwisc00d39e2014-03-30 21:07:25 +0200416 files, dirs = [], []
417 # Not all modules are required to have a __file__ attribute. See
418 # PEP 420 for more details.
419 if hasattr(os, '__file__'):
420 here = os.path.dirname(os.__file__)
421 files.extend(["LICENSE.txt", "LICENSE"])
422 dirs.extend([os.path.join(here, os.pardir), here, os.curdir])
Antoine Pitrou853395b2013-08-06 22:56:40 +0200423 builtins.license = _sitebuiltins._Printer(
R David Murray692ee9e2013-09-14 13:31:44 -0400424 "license",
Benjamin Petersond40f1362015-02-01 20:17:22 -0500425 "See https://www.python.org/psf/license/",
Martin v. Löwisc00d39e2014-03-30 21:07:25 +0200426 files, dirs)
Guido van Rossumd1252392000-09-05 04:39:55 +0000427
428
Brett Cannon0096e262004-06-05 01:12:51 +0000429def sethelper():
Antoine Pitrou853395b2013-08-06 22:56:40 +0200430 builtins.help = _sitebuiltins._Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000431
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200432def enablerlcompleter():
433 """Enable default readline configuration on interactive prompts, by
434 registering a sys.__interactivehook__.
435
436 If the readline module can be imported, the hook will set the Tab key
437 as completion key and register ~/.python_history as history file.
Martin Pantere26da7c2016-06-02 10:07:09 +0000438 This can be overridden in the sitecustomize or usercustomize module,
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200439 or in a PYTHONSTARTUP file.
440 """
441 def register_readline():
442 import atexit
443 try:
444 import readline
445 import rlcompleter
Brett Cannoncd171c82013-07-04 17:43:24 -0400446 except ImportError:
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200447 return
448
449 # Reading the initialization (config) file may not be enough to set a
R David Murray4a043012013-09-06 13:08:08 -0400450 # completion key, so we set one first and then read the file.
451 readline_doc = getattr(readline, '__doc__', '')
452 if readline_doc is not None and 'libedit' in readline_doc:
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200453 readline.parse_and_bind('bind ^I rl_complete')
454 else:
455 readline.parse_and_bind('tab: complete')
Mark Dickinson9d351332013-05-06 15:39:31 +0200456
457 try:
458 readline.read_init_file()
459 except OSError:
460 # An OSError here could have many causes, but the most likely one
461 # is that there's no .inputrc file (or .editrc file in the case of
462 # Mac OS X + libedit) in the expected location. In that case, we
463 # want to ignore the exception.
464 pass
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200465
Jason R. Coombs4d914902014-01-28 09:06:58 -0500466 if readline.get_current_history_length() == 0:
Antoine Pitrou5d23e6d2013-09-29 22:18:38 +0200467 # If no history was loaded, default to .python_history.
468 # The guard is necessary to avoid doubling history size at
469 # each interpreter exit when readline was already configured
470 # through a PYTHONSTARTUP hook, see:
471 # http://bugs.python.org/issue5845#msg198636
472 history = os.path.join(os.path.expanduser('~'),
473 '.python_history')
474 try:
475 readline.read_history_file(history)
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +0300476 except OSError:
Antoine Pitrou5d23e6d2013-09-29 22:18:38 +0200477 pass
Anthony Sottileb2499662018-08-06 01:28:19 -0700478
479 def write_history():
480 try:
481 readline.write_history_file(history)
Victor Stinner0ab917e2020-07-02 12:43:25 +0200482 except OSError:
483 # bpo-19891, bpo-41193: Home directory does not exist
484 # or is not writable, or the filesystem is read-only.
Anthony Sottileb2499662018-08-06 01:28:19 -0700485 pass
486
487 atexit.register(write_history)
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200488
489 sys.__interactivehook__ = register_readline
490
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100491def venv(known_paths):
492 global PREFIXES, ENABLE_USER_SITE
493
494 env = os.environ
Vinay Sajip28952442012-06-25 00:47:46 +0100495 if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in env:
Steve Dowera8474d02019-02-03 23:19:38 -0800496 executable = sys._base_executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100497 else:
498 executable = sys.executable
Vinay Sajip27e4b602012-11-23 19:16:49 +0000499 exe_dir, _ = os.path.split(os.path.abspath(executable))
500 site_prefix = os.path.dirname(exe_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100501 sys._home = None
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100502 conf_basename = 'pyvenv.cfg'
503 candidate_confs = [
504 conffile for conffile in (
Vinay Sajip27e4b602012-11-23 19:16:49 +0000505 os.path.join(exe_dir, conf_basename),
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100506 os.path.join(site_prefix, conf_basename)
507 )
508 if os.path.isfile(conffile)
509 ]
510
511 if candidate_confs:
512 virtual_conf = candidate_confs[0]
513 system_site = "true"
Vinay Sajipf223c532015-10-01 11:27:00 +0100514 # Issue 25185: Use UTF-8, as that's what the venv module uses when
515 # writing the file.
516 with open(virtual_conf, encoding='utf-8') as f:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100517 for line in f:
Serhiy Storchaka727ba7c2016-11-08 20:17:35 +0200518 if '=' in line:
519 key, _, value = line.partition('=')
520 key = key.strip().lower()
521 value = value.strip()
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100522 if key == 'include-system-site-packages':
523 system_site = value.lower()
524 elif key == 'home':
525 sys._home = value
526
527 sys.prefix = sys.exec_prefix = site_prefix
528
529 # Doing this here ensures venv takes precedence over user-site
530 addsitepackages(known_paths, [sys.prefix])
531
532 # addsitepackages will process site_prefix again if its in PREFIXES,
533 # but that's ok; known_paths will prevent anything being added twice
534 if system_site == "true":
535 PREFIXES.insert(0, sys.prefix)
536 else:
537 PREFIXES = [sys.prefix]
538 ENABLE_USER_SITE = False
539
540 return known_paths
541
542
Brett Cannon0096e262004-06-05 01:12:51 +0000543def execsitecustomize():
544 """Run custom site specific code, if available."""
545 try:
Victor Stinnere3560a72016-01-22 12:22:07 +0100546 try:
547 import sitecustomize
548 except ImportError as exc:
549 if exc.name == 'sitecustomize':
550 pass
551 else:
552 raise
Guido van Rossumb940e112007-01-10 16:19:56 +0000553 except Exception as err:
Steve Dower313523c2016-09-17 12:22:41 -0700554 if sys.flags.verbose:
Victor Stinner52f6dd72010-03-12 14:45:56 +0000555 sys.excepthook(*sys.exc_info())
556 else:
557 sys.stderr.write(
558 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
559 "%s: %s\n" %
560 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000561
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000562
Christian Heimes8dc226f2008-05-06 23:45:46 +0000563def execusercustomize():
564 """Run custom user specific code, if available."""
565 try:
Victor Stinnere3560a72016-01-22 12:22:07 +0100566 try:
567 import usercustomize
568 except ImportError as exc:
569 if exc.name == 'usercustomize':
570 pass
571 else:
572 raise
Victor Stinner52f6dd72010-03-12 14:45:56 +0000573 except Exception as err:
Steve Dower313523c2016-09-17 12:22:41 -0700574 if sys.flags.verbose:
Victor Stinner52f6dd72010-03-12 14:45:56 +0000575 sys.excepthook(*sys.exc_info())
576 else:
577 sys.stderr.write(
578 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
579 "%s: %s\n" %
580 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000581
582
Brett Cannon0096e262004-06-05 01:12:51 +0000583def main():
Éric Araujoc09fca62011-03-23 02:06:24 +0100584 """Add standard site-specific directories to the module search path.
585
586 This function is called automatically when this module is imported,
587 unless the python interpreter was started with the -S flag.
588 """
Christian Heimes8dc226f2008-05-06 23:45:46 +0000589 global ENABLE_USER_SITE
590
INADA Naoki2e4e0112017-03-15 00:52:19 +0900591 orig_path = sys.path[:]
Christian Heimes8dc226f2008-05-06 23:45:46 +0000592 known_paths = removeduppaths()
INADA Naoki2e4e0112017-03-15 00:52:19 +0900593 if orig_path != sys.path:
594 # removeduppaths() might make sys.path absolute.
595 # fix __file__ and __cached__ of already imported modules too.
596 abs_paths()
597
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100598 known_paths = venv(known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000599 if ENABLE_USER_SITE is None:
600 ENABLE_USER_SITE = check_enableusersite()
601 known_paths = addusersitepackages(known_paths)
602 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000603 setquit()
604 setcopyright()
605 sethelper()
Steve Dower313523c2016-09-17 12:22:41 -0700606 if not sys.flags.isolated:
607 enablerlcompleter()
Brett Cannon0096e262004-06-05 01:12:51 +0000608 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000609 if ENABLE_USER_SITE:
610 execusercustomize()
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000611
Steve Dower313523c2016-09-17 12:22:41 -0700612# Prevent extending of sys.path when python was started with -S and
Éric Araujoc09fca62011-03-23 02:06:24 +0100613# site is imported later.
614if not sys.flags.no_site:
615 main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000616
Christian Heimes8dc226f2008-05-06 23:45:46 +0000617def _script():
618 help = """\
619 %s [--user-base] [--user-site]
620
621 Without arguments print some useful information
622 With arguments print the value of USER_BASE and/or USER_SITE separated
623 by '%s'.
624
625 Exit codes with --user-base or --user-site:
626 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000627 1 - user site directory is disabled by user
Daniel Andersson40c01c32019-12-14 11:37:58 +0100628 2 - user site directory is disabled by super user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000629 or for security reasons
630 >2 - unknown error
631 """
632 args = sys.argv[1:]
633 if not args:
Meador Inge9a7a8112013-04-13 20:29:49 -0500634 user_base = getuserbase()
635 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000636 print("sys.path = [")
637 for dir in sys.path:
638 print(" %r," % (dir,))
639 print("]")
pxinwrab74c012020-12-21 06:27:42 +0800640 def exists(path):
641 if path is not None and os.path.isdir(path):
642 return "exists"
643 else:
644 return "doesn't exist"
645 print(f"USER_BASE: {user_base!r} ({exists(user_base)})")
646 print(f"USER_SITE: {user_site!r} ({exists(user_site)})")
647 print(f"ENABLE_USER_SITE: {ENABLE_USER_SITE!r}")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000648 sys.exit(0)
649
650 buffer = []
651 if '--user-base' in args:
652 buffer.append(USER_BASE)
653 if '--user-site' in args:
654 buffer.append(USER_SITE)
655
656 if buffer:
657 print(os.pathsep.join(buffer))
658 if ENABLE_USER_SITE:
659 sys.exit(0)
660 elif ENABLE_USER_SITE is False:
661 sys.exit(1)
662 elif ENABLE_USER_SITE is None:
663 sys.exit(2)
664 else:
665 sys.exit(3)
666 else:
667 import textwrap
668 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
669 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000670
671if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000672 _script()