blob: b6376357ea3689f6a3ff6f3d26ca4c7087333590 [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
Guido van Rossume57c96e1996-08-17 19:56:26 +000076
Christian Heimes8dc226f2008-05-06 23:45:46 +000077# Prefixes for site-packages; add additional prefixes like /usr/local here
78PREFIXES = [sys.prefix, sys.exec_prefix]
79# Enable per user site-packages directory
80# set it to False to disable the feature or True to force the feature
81ENABLE_USER_SITE = None
Tarek Ziadé4a608c02009-08-20 21:28:05 +000082
Christian Heimes8dc226f2008-05-06 23:45:46 +000083# for distutils.commands.install
Tarek Ziadé4a608c02009-08-20 21:28:05 +000084# These values are initialized by the getuserbase() and getusersitepackages()
85# functions, through the main() function when Python starts.
Christian Heimes8dc226f2008-05-06 23:45:46 +000086USER_SITE = None
87USER_BASE = None
88
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000089
Fred Drake38cb9f12000-09-28 16:52:36 +000090def makepath(*paths):
Victor Stinnerb103a932010-10-12 22:23:23 +000091 dir = os.path.join(*paths)
92 try:
93 dir = os.path.abspath(dir)
94 except OSError:
95 pass
Fred Drake1fb5ce02001-07-02 16:55:42 +000096 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000097
Christian Heimes8dc226f2008-05-06 23:45:46 +000098
Barry Warsaw28a691b2010-04-17 00:19:56 +000099def abs_paths():
100 """Set all module __file__ and __cached__ attributes to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +0000101 for m in set(sys.modules.values()):
Eric Snow32439d62015-05-02 19:15:18 -0600102 if (getattr(getattr(m, '__loader__', None), '__module__', None) not in
103 ('_frozen_importlib', '_frozen_importlib_external')):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000104 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +0000105 try:
106 m.__file__ = os.path.abspath(m.__file__)
Victor Stinnerb103a932010-10-12 22:23:23 +0000107 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000108 pass
109 try:
110 m.__cached__ = os.path.abspath(m.__cached__)
Victor Stinnerb103a932010-10-12 22:23:23 +0000111 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112 pass
Fred Drake38cb9f12000-09-28 16:52:36 +0000113
Christian Heimes8dc226f2008-05-06 23:45:46 +0000114
Brett Cannon0096e262004-06-05 01:12:51 +0000115def removeduppaths():
116 """ Remove duplicate entries from sys.path along with making them
117 absolute"""
118 # This ensures that the initial path provided by the interpreter contains
119 # only absolute pathnames, even if we're running from the build directory.
120 L = []
121 known_paths = set()
122 for dir in sys.path:
123 # Filter out duplicate paths (on case-insensitive file systems also
124 # if they only differ in case); turn relative paths into absolute
125 # paths.
126 dir, dircase = makepath(dir)
127 if not dircase in known_paths:
128 L.append(dir)
129 known_paths.add(dircase)
130 sys.path[:] = L
131 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000132
Christian Heimes8dc226f2008-05-06 23:45:46 +0000133
Fred Drake7f5296e2001-07-20 20:06:17 +0000134def _init_pathinfo():
Brett Cannon5f0507d2016-04-08 15:04:28 -0700135 """Return a set containing all existing file system items from sys.path."""
Brett Cannon0096e262004-06-05 01:12:51 +0000136 d = set()
Brett Cannon5f0507d2016-04-08 15:04:28 -0700137 for item in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000138 try:
Brett Cannon5f0507d2016-04-08 15:04:28 -0700139 if os.path.exists(item):
140 _, itemcase = makepath(item)
141 d.add(itemcase)
Brett Cannon0096e262004-06-05 01:12:51 +0000142 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000143 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000144 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000145
Christian Heimes8dc226f2008-05-06 23:45:46 +0000146
Brett Cannon0096e262004-06-05 01:12:51 +0000147def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000148 """Process a .pth file within the site-packages directory:
149 For each line in the file, either combine it with sitedir to a path
150 and add that to known_paths, or execute it if it starts with 'import '.
151 """
Brett Cannon0096e262004-06-05 01:12:51 +0000152 if known_paths is None:
Brett Cannon13252b82013-01-25 13:57:16 -0500153 known_paths = _init_pathinfo()
Brett Cannon5f0507d2016-04-08 15:04:28 -0700154 reset = True
Fred Drake7f5296e2001-07-20 20:06:17 +0000155 else:
Brett Cannon5f0507d2016-04-08 15:04:28 -0700156 reset = False
Brett Cannon0096e262004-06-05 01:12:51 +0000157 fullname = os.path.join(sitedir, name)
158 try:
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200159 f = open(fullname, "r")
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200160 except OSError:
Brett Cannon0096e262004-06-05 01:12:51 +0000161 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000162 with f:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000163 for n, line in enumerate(f):
Brett Cannon0096e262004-06-05 01:12:51 +0000164 if line.startswith("#"):
165 continue
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000166 try:
167 if line.startswith(("import ", "import\t")):
168 exec(line)
169 continue
170 line = line.rstrip()
171 dir, dircase = makepath(sitedir, line)
172 if not dircase in known_paths and os.path.exists(dir):
173 sys.path.append(dir)
174 known_paths.add(dircase)
Florent Xicluna54540ec2011-11-04 08:29:17 +0100175 except Exception:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000176 print("Error processing line {:d} of {}:\n".format(n+1, fullname),
177 file=sys.stderr)
Victor Stinner65532112012-02-21 22:10:16 +0100178 import traceback
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000179 for record in traceback.format_exception(*sys.exc_info()):
180 for line in record.splitlines():
181 print(' '+line, file=sys.stderr)
182 print("\nRemainder of file ignored", file=sys.stderr)
183 break
Brett Cannon0096e262004-06-05 01:12:51 +0000184 if reset:
185 known_paths = None
186 return known_paths
187
Christian Heimes8dc226f2008-05-06 23:45:46 +0000188
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000189def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000190 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
191 'sitedir'"""
192 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000193 known_paths = _init_pathinfo()
Brett Cannon5f0507d2016-04-08 15:04:28 -0700194 reset = True
Brett Cannon0096e262004-06-05 01:12:51 +0000195 else:
Brett Cannon5f0507d2016-04-08 15:04:28 -0700196 reset = False
Fred Drake1fb5ce02001-07-02 16:55:42 +0000197 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000198 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000199 sys.path.append(sitedir) # Add path component
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100200 known_paths.add(sitedircase)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000201 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 names = os.listdir(sitedir)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200203 except OSError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000205 names = [name for name in names if name.endswith(".pth")]
206 for name in sorted(names):
207 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000208 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000209 known_paths = None
210 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000211
Christian Heimes8dc226f2008-05-06 23:45:46 +0000212
213def check_enableusersite():
214 """Check if user site directory is safe for inclusion
215
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000216 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000217 process uid/gid equal to effective uid/gid.
218
219 None: Disabled for security reasons
220 False: Disabled by user (command line option)
221 True: Safe and enabled
222 """
223 if sys.flags.no_user_site:
224 return False
225
226 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
227 # check process uid == effective uid
228 if os.geteuid() != os.getuid():
229 return None
230 if hasattr(os, "getgid") and hasattr(os, "getegid"):
231 # check process gid == effective gid
232 if os.getegid() != os.getgid():
233 return None
234
235 return True
236
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000237def getuserbase():
238 """Returns the `user base` directory path.
239
240 The `user base` directory can be used to store data. If the global
241 variable ``USER_BASE`` is not initialized yet, this function will also set
242 it.
243 """
244 global USER_BASE
245 if USER_BASE is not None:
246 return USER_BASE
Tarek Ziadéedacea32010-01-29 11:41:03 +0000247 from sysconfig import get_config_var
248 USER_BASE = get_config_var('userbase')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000249 return USER_BASE
250
251def getusersitepackages():
252 """Returns the user-specific site-packages directory path.
253
254 If the global variable ``USER_SITE`` is not initialized yet, this
255 function will also set it.
256 """
257 global USER_SITE
258 user_base = getuserbase() # this will also set USER_BASE
259
260 if USER_SITE is not None:
261 return USER_SITE
262
Tarek Ziadéedacea32010-01-29 11:41:03 +0000263 from sysconfig import get_path
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000264
265 if sys.platform == 'darwin':
266 from sysconfig import get_config_var
267 if get_config_var('PYTHONFRAMEWORK'):
268 USER_SITE = get_path('purelib', 'osx_framework_user')
269 return USER_SITE
270
Tarek Ziadéedacea32010-01-29 11:41:03 +0000271 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000272 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000273
274def addusersitepackages(known_paths):
275 """Add a per user site-package to sys.path
276
277 Each user has its own python directory with site-packages in the
278 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000279 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000280 # get the per user site-package path
281 # this call will also make sure USER_BASE and USER_SITE are set
282 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000283
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000284 if ENABLE_USER_SITE and os.path.isdir(user_site):
285 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000286 return known_paths
287
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100288def getsitepackages(prefixes=None):
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400289 """Returns a list containing all global site-packages directories.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000290
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100291 For each directory present in ``prefixes`` (or the global ``PREFIXES``),
292 this function will find its `site-packages` subdirectory depending on the
293 system environment, and will return a list of full paths.
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000294 """
295 sitepackages = []
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000296 seen = set()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000297
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100298 if prefixes is None:
299 prefixes = PREFIXES
300
301 for prefix in prefixes:
Christian Heimes8dc226f2008-05-06 23:45:46 +0000302 if not prefix or prefix in seen:
303 continue
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000304 seen.add(prefix)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000305
Christian Heimesde0b9622012-11-19 00:59:39 +0100306 if os.sep == '/':
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000307 sitepackages.append(os.path.join(prefix, "lib",
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200308 "python%d.%d" % sys.version_info[:2],
Christian Heimes8dc226f2008-05-06 23:45:46 +0000309 "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000310 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000311 sitepackages.append(prefix)
312 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000313 if sys.platform == "darwin":
314 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000315 # locations.
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000316 from sysconfig import get_config_var
317 framework = get_config_var("PYTHONFRAMEWORK")
Ronald Oussorenbda46722010-08-01 09:02:50 +0000318 if framework:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000319 sitepackages.append(
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000320 os.path.join("/Library", framework,
Serhiy Storchaka885bdc42016-02-11 13:10:36 +0200321 '%d.%d' % sys.version_info[:2], "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000322 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000323
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100324def addsitepackages(known_paths, prefixes=None):
Antoine Pitrou9e82b172014-06-12 19:41:30 -0400325 """Add site-packages to sys.path"""
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100326 for sitedir in getsitepackages(prefixes):
Christian Heimes8dc226f2008-05-06 23:45:46 +0000327 if os.path.isdir(sitedir):
328 addsitedir(sitedir, known_paths)
329
330 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000331
Brett Cannon0096e262004-06-05 01:12:51 +0000332def setquit():
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000333 """Define new builtins 'quit' and 'exit'.
334
335 These are objects which make the interpreter exit when called.
336 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000337
Brett Cannon0096e262004-06-05 01:12:51 +0000338 """
339 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000340 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000341 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000342 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000343 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000344 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000345
Antoine Pitrou853395b2013-08-06 22:56:40 +0200346 builtins.quit = _sitebuiltins.Quitter('quit', eof)
347 builtins.exit = _sitebuiltins.Quitter('exit', eof)
Brett Cannon0096e262004-06-05 01:12:51 +0000348
349
Brett Cannon0096e262004-06-05 01:12:51 +0000350def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000351 """Set 'copyright' and 'credits' in builtins"""
Antoine Pitrou853395b2013-08-06 22:56:40 +0200352 builtins.copyright = _sitebuiltins._Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000353 if sys.platform[:4] == 'java':
Antoine Pitrou853395b2013-08-06 22:56:40 +0200354 builtins.credits = _sitebuiltins._Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000355 "credits",
Antoine Pitrouf93c7b82013-08-01 19:46:04 +0200356 "Jython is maintained by the Jython developers (www.jython.org).")
Brett Cannon0096e262004-06-05 01:12:51 +0000357 else:
Antoine Pitrou853395b2013-08-06 22:56:40 +0200358 builtins.credits = _sitebuiltins._Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000359 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
Antoine Pitrouf93c7b82013-08-01 19:46:04 +0200360 for supporting Python development. See www.python.org for more information.""")
Martin v. Löwisc00d39e2014-03-30 21:07:25 +0200361 files, dirs = [], []
362 # Not all modules are required to have a __file__ attribute. See
363 # PEP 420 for more details.
364 if hasattr(os, '__file__'):
365 here = os.path.dirname(os.__file__)
366 files.extend(["LICENSE.txt", "LICENSE"])
367 dirs.extend([os.path.join(here, os.pardir), here, os.curdir])
Antoine Pitrou853395b2013-08-06 22:56:40 +0200368 builtins.license = _sitebuiltins._Printer(
R David Murray692ee9e2013-09-14 13:31:44 -0400369 "license",
Benjamin Petersond40f1362015-02-01 20:17:22 -0500370 "See https://www.python.org/psf/license/",
Martin v. Löwisc00d39e2014-03-30 21:07:25 +0200371 files, dirs)
Guido van Rossumd1252392000-09-05 04:39:55 +0000372
373
Brett Cannon0096e262004-06-05 01:12:51 +0000374def sethelper():
Antoine Pitrou853395b2013-08-06 22:56:40 +0200375 builtins.help = _sitebuiltins._Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000376
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200377def enablerlcompleter():
378 """Enable default readline configuration on interactive prompts, by
379 registering a sys.__interactivehook__.
380
381 If the readline module can be imported, the hook will set the Tab key
382 as completion key and register ~/.python_history as history file.
Martin Pantere26da7c2016-06-02 10:07:09 +0000383 This can be overridden in the sitecustomize or usercustomize module,
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200384 or in a PYTHONSTARTUP file.
385 """
386 def register_readline():
387 import atexit
388 try:
389 import readline
390 import rlcompleter
Brett Cannoncd171c82013-07-04 17:43:24 -0400391 except ImportError:
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200392 return
393
394 # Reading the initialization (config) file may not be enough to set a
R David Murray4a043012013-09-06 13:08:08 -0400395 # completion key, so we set one first and then read the file.
396 readline_doc = getattr(readline, '__doc__', '')
397 if readline_doc is not None and 'libedit' in readline_doc:
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200398 readline.parse_and_bind('bind ^I rl_complete')
399 else:
400 readline.parse_and_bind('tab: complete')
Mark Dickinson9d351332013-05-06 15:39:31 +0200401
402 try:
403 readline.read_init_file()
404 except OSError:
405 # An OSError here could have many causes, but the most likely one
406 # is that there's no .inputrc file (or .editrc file in the case of
407 # Mac OS X + libedit) in the expected location. In that case, we
408 # want to ignore the exception.
409 pass
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200410
Jason R. Coombs4d914902014-01-28 09:06:58 -0500411 if readline.get_current_history_length() == 0:
Antoine Pitrou5d23e6d2013-09-29 22:18:38 +0200412 # If no history was loaded, default to .python_history.
413 # The guard is necessary to avoid doubling history size at
414 # each interpreter exit when readline was already configured
415 # through a PYTHONSTARTUP hook, see:
416 # http://bugs.python.org/issue5845#msg198636
417 history = os.path.join(os.path.expanduser('~'),
418 '.python_history')
419 try:
420 readline.read_history_file(history)
421 except IOError:
422 pass
423 atexit.register(readline.write_history_file, history)
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200424
425 sys.__interactivehook__ = register_readline
426
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200427CONFIG_LINE = r'^(?P<key>(\w|[-_])+)\s*=\s*(?P<value>.*)\s*$'
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100428
429def venv(known_paths):
430 global PREFIXES, ENABLE_USER_SITE
431
432 env = os.environ
Vinay Sajip28952442012-06-25 00:47:46 +0100433 if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in env:
434 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100435 else:
436 executable = sys.executable
Vinay Sajip27e4b602012-11-23 19:16:49 +0000437 exe_dir, _ = os.path.split(os.path.abspath(executable))
438 site_prefix = os.path.dirname(exe_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100439 sys._home = None
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100440 conf_basename = 'pyvenv.cfg'
441 candidate_confs = [
442 conffile for conffile in (
Vinay Sajip27e4b602012-11-23 19:16:49 +0000443 os.path.join(exe_dir, conf_basename),
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100444 os.path.join(site_prefix, conf_basename)
445 )
446 if os.path.isfile(conffile)
447 ]
448
449 if candidate_confs:
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200450 import re
451 config_line = re.compile(CONFIG_LINE)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100452 virtual_conf = candidate_confs[0]
453 system_site = "true"
Vinay Sajipf223c532015-10-01 11:27:00 +0100454 # Issue 25185: Use UTF-8, as that's what the venv module uses when
455 # writing the file.
456 with open(virtual_conf, encoding='utf-8') as f:
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100457 for line in f:
458 line = line.strip()
Christian Heimesbfc3a9a2013-10-12 00:28:17 +0200459 m = config_line.match(line)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100460 if m:
461 d = m.groupdict()
462 key, value = d['key'].lower(), d['value']
463 if key == 'include-system-site-packages':
464 system_site = value.lower()
465 elif key == 'home':
466 sys._home = value
467
468 sys.prefix = sys.exec_prefix = site_prefix
469
470 # Doing this here ensures venv takes precedence over user-site
471 addsitepackages(known_paths, [sys.prefix])
472
473 # addsitepackages will process site_prefix again if its in PREFIXES,
474 # but that's ok; known_paths will prevent anything being added twice
475 if system_site == "true":
476 PREFIXES.insert(0, sys.prefix)
477 else:
478 PREFIXES = [sys.prefix]
479 ENABLE_USER_SITE = False
480
481 return known_paths
482
483
Brett Cannon0096e262004-06-05 01:12:51 +0000484def execsitecustomize():
485 """Run custom site specific code, if available."""
486 try:
Victor Stinnere3560a72016-01-22 12:22:07 +0100487 try:
488 import sitecustomize
489 except ImportError as exc:
490 if exc.name == 'sitecustomize':
491 pass
492 else:
493 raise
Guido van Rossumb940e112007-01-10 16:19:56 +0000494 except Exception as err:
Steve Dower313523c2016-09-17 12:22:41 -0700495 if sys.flags.verbose:
Victor Stinner52f6dd72010-03-12 14:45:56 +0000496 sys.excepthook(*sys.exc_info())
497 else:
498 sys.stderr.write(
499 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
500 "%s: %s\n" %
501 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000502
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000503
Christian Heimes8dc226f2008-05-06 23:45:46 +0000504def execusercustomize():
505 """Run custom user specific code, if available."""
506 try:
Victor Stinnere3560a72016-01-22 12:22:07 +0100507 try:
508 import usercustomize
509 except ImportError as exc:
510 if exc.name == 'usercustomize':
511 pass
512 else:
513 raise
Victor Stinner52f6dd72010-03-12 14:45:56 +0000514 except Exception as err:
Steve Dower313523c2016-09-17 12:22:41 -0700515 if sys.flags.verbose:
Victor Stinner52f6dd72010-03-12 14:45:56 +0000516 sys.excepthook(*sys.exc_info())
517 else:
518 sys.stderr.write(
519 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
520 "%s: %s\n" %
521 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000522
523
Brett Cannon0096e262004-06-05 01:12:51 +0000524def main():
Éric Araujoc09fca62011-03-23 02:06:24 +0100525 """Add standard site-specific directories to the module search path.
526
527 This function is called automatically when this module is imported,
528 unless the python interpreter was started with the -S flag.
529 """
Christian Heimes8dc226f2008-05-06 23:45:46 +0000530 global ENABLE_USER_SITE
531
Barry Warsaw28a691b2010-04-17 00:19:56 +0000532 abs_paths()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000533 known_paths = removeduppaths()
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100534 known_paths = venv(known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000535 if ENABLE_USER_SITE is None:
536 ENABLE_USER_SITE = check_enableusersite()
537 known_paths = addusersitepackages(known_paths)
538 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000539 setquit()
540 setcopyright()
541 sethelper()
Steve Dower313523c2016-09-17 12:22:41 -0700542 if not sys.flags.isolated:
543 enablerlcompleter()
Brett Cannon0096e262004-06-05 01:12:51 +0000544 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000545 if ENABLE_USER_SITE:
546 execusercustomize()
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000547
Steve Dower313523c2016-09-17 12:22:41 -0700548# Prevent extending of sys.path when python was started with -S and
Éric Araujoc09fca62011-03-23 02:06:24 +0100549# site is imported later.
550if not sys.flags.no_site:
551 main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000552
Christian Heimes8dc226f2008-05-06 23:45:46 +0000553def _script():
554 help = """\
555 %s [--user-base] [--user-site]
556
557 Without arguments print some useful information
558 With arguments print the value of USER_BASE and/or USER_SITE separated
559 by '%s'.
560
561 Exit codes with --user-base or --user-site:
562 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000563 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000564 2 - uses site directory is disabled by super user
565 or for security reasons
566 >2 - unknown error
567 """
568 args = sys.argv[1:]
569 if not args:
Meador Inge9a7a8112013-04-13 20:29:49 -0500570 user_base = getuserbase()
571 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000572 print("sys.path = [")
573 for dir in sys.path:
574 print(" %r," % (dir,))
575 print("]")
Meador Inge9a7a8112013-04-13 20:29:49 -0500576 print("USER_BASE: %r (%s)" % (user_base,
577 "exists" if os.path.isdir(user_base) else "doesn't exist"))
578 print("USER_SITE: %r (%s)" % (user_site,
579 "exists" if os.path.isdir(user_site) else "doesn't exist"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000580 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
581 sys.exit(0)
582
583 buffer = []
584 if '--user-base' in args:
585 buffer.append(USER_BASE)
586 if '--user-site' in args:
587 buffer.append(USER_SITE)
588
589 if buffer:
590 print(os.pathsep.join(buffer))
591 if ENABLE_USER_SITE:
592 sys.exit(0)
593 elif ENABLE_USER_SITE is False:
594 sys.exit(1)
595 elif ENABLE_USER_SITE is None:
596 sys.exit(2)
597 else:
598 sys.exit(3)
599 else:
600 import textwrap
601 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
602 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000603
604if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000605 _script()