blob: 4fb1058a1e882ea8d7d3ca399f8c8042070e05cc [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
10lib/python<version>/site-packages as well as lib/site-python.
11On 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
Vinay Sajipabd344c2012-07-03 16:33:57 +010018it is also checked for site-packages and site-python (sys.base_prefix and
19sys.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
62completion for systems that support it. This can be overriden in
63sitecustomize, usercustomize or PYTHONSTARTUP.
64
65After these operations, an attempt is made to import a module
Guido van Rossumf30bec71997-08-29 22:30:45 +000066named sitecustomize, which can perform arbitrary additional
67site-specific customizations. If this import fails with an
68ImportError exception, it is silently ignored.
Guido van Rossume57c96e1996-08-17 19:56:26 +000069"""
70
Brett Cannon0096e262004-06-05 01:12:51 +000071import sys
72import os
Georg Brandl1a3284e2007-12-02 09:40:06 +000073import builtins
Antoine Pitrou853395b2013-08-06 22:56:40 +020074import _sitebuiltins
Guido van Rossume57c96e1996-08-17 19:56:26 +000075
Christian Heimes8dc226f2008-05-06 23:45:46 +000076# Prefixes for site-packages; add additional prefixes like /usr/local here
77PREFIXES = [sys.prefix, sys.exec_prefix]
78# Enable per user site-packages directory
79# set it to False to disable the feature or True to force the feature
80ENABLE_USER_SITE = None
Tarek Ziadé4a608c02009-08-20 21:28:05 +000081
Christian Heimes8dc226f2008-05-06 23:45:46 +000082# for distutils.commands.install
Tarek Ziadé4a608c02009-08-20 21:28:05 +000083# These values are initialized by the getuserbase() and getusersitepackages()
84# functions, through the main() function when Python starts.
Christian Heimes8dc226f2008-05-06 23:45:46 +000085USER_SITE = None
86USER_BASE = None
87
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000088
Fred Drake38cb9f12000-09-28 16:52:36 +000089def makepath(*paths):
Victor Stinnerb103a932010-10-12 22:23:23 +000090 dir = os.path.join(*paths)
91 try:
92 dir = os.path.abspath(dir)
93 except OSError:
94 pass
Fred Drake1fb5ce02001-07-02 16:55:42 +000095 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000096
Christian Heimes8dc226f2008-05-06 23:45:46 +000097
Barry Warsaw28a691b2010-04-17 00:19:56 +000098def abs_paths():
99 """Set all module __file__ and __cached__ attributes to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +0000100 for m in set(sys.modules.values()):
Brett Cannonfd074152012-04-14 14:10:13 -0400101 if (getattr(getattr(m, '__loader__', None), '__module__', None) !=
102 '_frozen_importlib'):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000103 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +0000104 try:
105 m.__file__ = os.path.abspath(m.__file__)
Victor Stinnerb103a932010-10-12 22:23:23 +0000106 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000107 pass
108 try:
109 m.__cached__ = os.path.abspath(m.__cached__)
Victor Stinnerb103a932010-10-12 22:23:23 +0000110 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000111 pass
Fred Drake38cb9f12000-09-28 16:52:36 +0000112
Christian Heimes8dc226f2008-05-06 23:45:46 +0000113
Brett Cannon0096e262004-06-05 01:12:51 +0000114def removeduppaths():
115 """ Remove duplicate entries from sys.path along with making them
116 absolute"""
117 # This ensures that the initial path provided by the interpreter contains
118 # only absolute pathnames, even if we're running from the build directory.
119 L = []
120 known_paths = set()
121 for dir in sys.path:
122 # Filter out duplicate paths (on case-insensitive file systems also
123 # if they only differ in case); turn relative paths into absolute
124 # paths.
125 dir, dircase = makepath(dir)
126 if not dircase in known_paths:
127 L.append(dir)
128 known_paths.add(dircase)
129 sys.path[:] = L
130 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000131
Christian Heimes8dc226f2008-05-06 23:45:46 +0000132
Fred Drake7f5296e2001-07-20 20:06:17 +0000133def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000134 """Return a set containing all existing directory entries from sys.path"""
135 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000136 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000137 try:
138 if os.path.isdir(dir):
139 dir, dircase = makepath(dir)
140 d.add(dircase)
141 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000142 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000143 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000144
Christian Heimes8dc226f2008-05-06 23:45:46 +0000145
Brett Cannon0096e262004-06-05 01:12:51 +0000146def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000147 """Process a .pth file within the site-packages directory:
148 For each line in the file, either combine it with sitedir to a path
149 and add that to known_paths, or execute it if it starts with 'import '.
150 """
Brett Cannon0096e262004-06-05 01:12:51 +0000151 if known_paths is None:
Brett Cannon13252b82013-01-25 13:57:16 -0500152 known_paths = _init_pathinfo()
Fred Drake7f5296e2001-07-20 20:06:17 +0000153 reset = 1
154 else:
155 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000156 fullname = os.path.join(sitedir, name)
157 try:
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200158 f = open(fullname, "r")
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200159 except OSError:
Brett Cannon0096e262004-06-05 01:12:51 +0000160 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000161 with f:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000162 for n, line in enumerate(f):
Brett Cannon0096e262004-06-05 01:12:51 +0000163 if line.startswith("#"):
164 continue
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000165 try:
166 if line.startswith(("import ", "import\t")):
167 exec(line)
168 continue
169 line = line.rstrip()
170 dir, dircase = makepath(sitedir, line)
171 if not dircase in known_paths and os.path.exists(dir):
172 sys.path.append(dir)
173 known_paths.add(dircase)
Florent Xicluna54540ec2011-11-04 08:29:17 +0100174 except Exception:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000175 print("Error processing line {:d} of {}:\n".format(n+1, fullname),
176 file=sys.stderr)
Victor Stinner65532112012-02-21 22:10:16 +0100177 import traceback
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000178 for record in traceback.format_exception(*sys.exc_info()):
179 for line in record.splitlines():
180 print(' '+line, file=sys.stderr)
181 print("\nRemainder of file ignored", file=sys.stderr)
182 break
Brett Cannon0096e262004-06-05 01:12:51 +0000183 if reset:
184 known_paths = None
185 return known_paths
186
Christian Heimes8dc226f2008-05-06 23:45:46 +0000187
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000188def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000189 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
190 'sitedir'"""
191 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000192 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000193 reset = 1
194 else:
195 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000196 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000197 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 sys.path.append(sitedir) # Add path component
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100199 known_paths.add(sitedircase)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000200 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000201 names = os.listdir(sitedir)
Andrew Svetlovad28c7f2012-12-18 22:02:39 +0200202 except OSError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000203 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000204 names = [name for name in names if name.endswith(".pth")]
205 for name in sorted(names):
206 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000207 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000208 known_paths = None
209 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000210
Christian Heimes8dc226f2008-05-06 23:45:46 +0000211
212def check_enableusersite():
213 """Check if user site directory is safe for inclusion
214
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000215 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000216 process uid/gid equal to effective uid/gid.
217
218 None: Disabled for security reasons
219 False: Disabled by user (command line option)
220 True: Safe and enabled
221 """
222 if sys.flags.no_user_site:
223 return False
224
225 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
226 # check process uid == effective uid
227 if os.geteuid() != os.getuid():
228 return None
229 if hasattr(os, "getgid") and hasattr(os, "getegid"):
230 # check process gid == effective gid
231 if os.getegid() != os.getgid():
232 return None
233
234 return True
235
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000236def getuserbase():
237 """Returns the `user base` directory path.
238
239 The `user base` directory can be used to store data. If the global
240 variable ``USER_BASE`` is not initialized yet, this function will also set
241 it.
242 """
243 global USER_BASE
244 if USER_BASE is not None:
245 return USER_BASE
Tarek Ziadéedacea32010-01-29 11:41:03 +0000246 from sysconfig import get_config_var
247 USER_BASE = get_config_var('userbase')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000248 return USER_BASE
249
250def getusersitepackages():
251 """Returns the user-specific site-packages directory path.
252
253 If the global variable ``USER_SITE`` is not initialized yet, this
254 function will also set it.
255 """
256 global USER_SITE
257 user_base = getuserbase() # this will also set USER_BASE
258
259 if USER_SITE is not None:
260 return USER_SITE
261
Tarek Ziadéedacea32010-01-29 11:41:03 +0000262 from sysconfig import get_path
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000263
264 if sys.platform == 'darwin':
265 from sysconfig import get_config_var
266 if get_config_var('PYTHONFRAMEWORK'):
267 USER_SITE = get_path('purelib', 'osx_framework_user')
268 return USER_SITE
269
Tarek Ziadéedacea32010-01-29 11:41:03 +0000270 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000271 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000272
273def addusersitepackages(known_paths):
274 """Add a per user site-package to sys.path
275
276 Each user has its own python directory with site-packages in the
277 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000278 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000279 # get the per user site-package path
280 # this call will also make sure USER_BASE and USER_SITE are set
281 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000282
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000283 if ENABLE_USER_SITE and os.path.isdir(user_site):
284 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000285 return known_paths
286
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100287def getsitepackages(prefixes=None):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000288 """Returns a list containing all global site-packages directories
289 (and possibly site-python).
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",
Christian Heimes8dc226f2008-05-06 23:45:46 +0000308 "python" + sys.version[:3],
309 "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000310 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000311 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000312 sitepackages.append(prefix)
313 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000314 if sys.platform == "darwin":
315 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000316 # locations.
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000317 from sysconfig import get_config_var
318 framework = get_config_var("PYTHONFRAMEWORK")
Ronald Oussorenbda46722010-08-01 09:02:50 +0000319 if framework:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000320 sitepackages.append(
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000321 os.path.join("/Library", framework,
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000322 sys.version[:3], "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000323 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000324
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100325def addsitepackages(known_paths, prefixes=None):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000326 """Add site-packages (and possibly site-python) to sys.path"""
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100327 for sitedir in getsitepackages(prefixes):
Christian Heimes8dc226f2008-05-06 23:45:46 +0000328 if os.path.isdir(sitedir):
Antoine Pitrou3b2f0f02013-10-25 21:39:26 +0200329 if "site-python" in sitedir:
330 import warnings
331 warnings.warn('"site-python" directories will not be '
332 'supported in 3.5 anymore',
333 DeprecationWarning)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000334 addsitedir(sitedir, known_paths)
335
336 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000337
Brett Cannon0096e262004-06-05 01:12:51 +0000338def setquit():
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000339 """Define new builtins 'quit' and 'exit'.
340
341 These are objects which make the interpreter exit when called.
342 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000343
Brett Cannon0096e262004-06-05 01:12:51 +0000344 """
345 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000346 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000347 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000348 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000349 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000350 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000351
Antoine Pitrou853395b2013-08-06 22:56:40 +0200352 builtins.quit = _sitebuiltins.Quitter('quit', eof)
353 builtins.exit = _sitebuiltins.Quitter('exit', eof)
Brett Cannon0096e262004-06-05 01:12:51 +0000354
355
Brett Cannon0096e262004-06-05 01:12:51 +0000356def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000357 """Set 'copyright' and 'credits' in builtins"""
Antoine Pitrou853395b2013-08-06 22:56:40 +0200358 builtins.copyright = _sitebuiltins._Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000359 if sys.platform[:4] == 'java':
Antoine Pitrou853395b2013-08-06 22:56:40 +0200360 builtins.credits = _sitebuiltins._Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000361 "credits",
Antoine Pitrouf93c7b82013-08-01 19:46:04 +0200362 "Jython is maintained by the Jython developers (www.jython.org).")
Brett Cannon0096e262004-06-05 01:12:51 +0000363 else:
Antoine Pitrou853395b2013-08-06 22:56:40 +0200364 builtins.credits = _sitebuiltins._Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000365 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
Antoine Pitrouf93c7b82013-08-01 19:46:04 +0200366 for supporting Python development. See www.python.org for more information.""")
Brett Cannon0096e262004-06-05 01:12:51 +0000367 here = os.path.dirname(os.__file__)
Antoine Pitrou853395b2013-08-06 22:56:40 +0200368 builtins.license = _sitebuiltins._Printer(
R David Murray692ee9e2013-09-14 13:31:44 -0400369 "license",
370 "See http://www.python.org/download/releases/%.5s/license" % sys.version,
Brett Cannon0096e262004-06-05 01:12:51 +0000371 ["LICENSE.txt", "LICENSE"],
Antoine Pitrouf93c7b82013-08-01 19:46:04 +0200372 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000373
374
Brett Cannon0096e262004-06-05 01:12:51 +0000375def sethelper():
Antoine Pitrou853395b2013-08-06 22:56:40 +0200376 builtins.help = _sitebuiltins._Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000377
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200378def enablerlcompleter():
379 """Enable default readline configuration on interactive prompts, by
380 registering a sys.__interactivehook__.
381
382 If the readline module can be imported, the hook will set the Tab key
383 as completion key and register ~/.python_history as history file.
384 This can be overriden in the sitecustomize or usercustomize module,
385 or in a PYTHONSTARTUP file.
386 """
387 def register_readline():
388 import atexit
389 try:
390 import readline
391 import rlcompleter
Brett Cannoncd171c82013-07-04 17:43:24 -0400392 except ImportError:
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200393 return
394
395 # Reading the initialization (config) file may not be enough to set a
R David Murray4a043012013-09-06 13:08:08 -0400396 # completion key, so we set one first and then read the file.
397 readline_doc = getattr(readline, '__doc__', '')
398 if readline_doc is not None and 'libedit' in readline_doc:
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200399 readline.parse_and_bind('bind ^I rl_complete')
400 else:
401 readline.parse_and_bind('tab: complete')
Mark Dickinson9d351332013-05-06 15:39:31 +0200402
403 try:
404 readline.read_init_file()
405 except OSError:
406 # An OSError here could have many causes, but the most likely one
407 # is that there's no .inputrc file (or .editrc file in the case of
408 # Mac OS X + libedit) in the expected location. In that case, we
409 # want to ignore the exception.
410 pass
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200411
Jason R. Coombs4d914902014-01-28 09:06:58 -0500412 if readline.get_current_history_length() == 0:
Antoine Pitrou5d23e6d2013-09-29 22:18:38 +0200413 # If no history was loaded, default to .python_history.
414 # The guard is necessary to avoid doubling history size at
415 # each interpreter exit when readline was already configured
416 # through a PYTHONSTARTUP hook, see:
417 # http://bugs.python.org/issue5845#msg198636
418 history = os.path.join(os.path.expanduser('~'),
419 '.python_history')
420 try:
421 readline.read_history_file(history)
422 except IOError:
423 pass
424 atexit.register(readline.write_history_file, history)
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200425
426 sys.__interactivehook__ = register_readline
427
Brett Cannon0096e262004-06-05 01:12:51 +0000428def aliasmbcs():
429 """On Windows, some default encodings are not provided by Python,
430 while they are always available as "mbcs" in each locale. Make
431 them usable by aliasing to "mbcs" in such a case."""
432 if sys.platform == 'win32':
Antoine Pitroufd4722c2013-10-12 00:13:50 +0200433 import _bootlocale, codecs
434 enc = _bootlocale.getpreferredencoding(False)
Brett Cannon0096e262004-06-05 01:12:51 +0000435 if enc.startswith('cp'): # "cp***" ?
436 try:
437 codecs.lookup(enc)
438 except LookupError:
439 import encodings
440 encodings._cache[enc] = encodings._unknown
441 encodings.aliases.aliases[enc] = 'mbcs'
442
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200443CONFIG_LINE = r'^(?P<key>(\w|[-_])+)\s*=\s*(?P<value>.*)\s*$'
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100444
445def venv(known_paths):
446 global PREFIXES, ENABLE_USER_SITE
447
448 env = os.environ
Vinay Sajip28952442012-06-25 00:47:46 +0100449 if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in env:
450 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100451 else:
452 executable = sys.executable
Vinay Sajip27e4b602012-11-23 19:16:49 +0000453 exe_dir, _ = os.path.split(os.path.abspath(executable))
454 site_prefix = os.path.dirname(exe_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100455 sys._home = None
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100456 conf_basename = 'pyvenv.cfg'
457 candidate_confs = [
458 conffile for conffile in (
Vinay Sajip27e4b602012-11-23 19:16:49 +0000459 os.path.join(exe_dir, conf_basename),
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100460 os.path.join(site_prefix, conf_basename)
461 )
462 if os.path.isfile(conffile)
463 ]
464
465 if candidate_confs:
Christian Heimes8c9cd5a2013-10-12 00:24:55 +0200466 import re
467 config_line = re.compile(CONFIG_LINE)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100468 virtual_conf = candidate_confs[0]
469 system_site = "true"
470 with open(virtual_conf) as f:
471 for line in f:
472 line = line.strip()
Christian Heimesbfc3a9a2013-10-12 00:28:17 +0200473 m = config_line.match(line)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100474 if m:
475 d = m.groupdict()
476 key, value = d['key'].lower(), d['value']
477 if key == 'include-system-site-packages':
478 system_site = value.lower()
479 elif key == 'home':
480 sys._home = value
481
482 sys.prefix = sys.exec_prefix = site_prefix
483
484 # Doing this here ensures venv takes precedence over user-site
485 addsitepackages(known_paths, [sys.prefix])
486
487 # addsitepackages will process site_prefix again if its in PREFIXES,
488 # but that's ok; known_paths will prevent anything being added twice
489 if system_site == "true":
490 PREFIXES.insert(0, sys.prefix)
491 else:
492 PREFIXES = [sys.prefix]
493 ENABLE_USER_SITE = False
494
495 return known_paths
496
497
Brett Cannon0096e262004-06-05 01:12:51 +0000498def execsitecustomize():
499 """Run custom site specific code, if available."""
500 try:
501 import sitecustomize
Brett Cannoncd171c82013-07-04 17:43:24 -0400502 except ImportError:
Brett Cannon0096e262004-06-05 01:12:51 +0000503 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000504 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000505 if os.environ.get("PYTHONVERBOSE"):
Victor Stinner52f6dd72010-03-12 14:45:56 +0000506 sys.excepthook(*sys.exc_info())
507 else:
508 sys.stderr.write(
509 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
510 "%s: %s\n" %
511 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000512
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000513
Christian Heimes8dc226f2008-05-06 23:45:46 +0000514def execusercustomize():
515 """Run custom user specific code, if available."""
516 try:
517 import usercustomize
Brett Cannoncd171c82013-07-04 17:43:24 -0400518 except ImportError:
Christian Heimes8dc226f2008-05-06 23:45:46 +0000519 pass
Victor Stinner52f6dd72010-03-12 14:45:56 +0000520 except Exception as err:
521 if os.environ.get("PYTHONVERBOSE"):
522 sys.excepthook(*sys.exc_info())
523 else:
524 sys.stderr.write(
525 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
526 "%s: %s\n" %
527 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000528
529
Brett Cannon0096e262004-06-05 01:12:51 +0000530def main():
Éric Araujoc09fca62011-03-23 02:06:24 +0100531 """Add standard site-specific directories to the module search path.
532
533 This function is called automatically when this module is imported,
534 unless the python interpreter was started with the -S flag.
535 """
Christian Heimes8dc226f2008-05-06 23:45:46 +0000536 global ENABLE_USER_SITE
537
Barry Warsaw28a691b2010-04-17 00:19:56 +0000538 abs_paths()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000539 known_paths = removeduppaths()
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100540 known_paths = venv(known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000541 if ENABLE_USER_SITE is None:
542 ENABLE_USER_SITE = check_enableusersite()
543 known_paths = addusersitepackages(known_paths)
544 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000545 setquit()
546 setcopyright()
547 sethelper()
Antoine Pitrou1a6cb302013-05-04 20:08:35 +0200548 enablerlcompleter()
Brett Cannon0096e262004-06-05 01:12:51 +0000549 aliasmbcs()
Brett Cannon0096e262004-06-05 01:12:51 +0000550 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000551 if ENABLE_USER_SITE:
552 execusercustomize()
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000553
Éric Araujoc09fca62011-03-23 02:06:24 +0100554# Prevent edition of sys.path when python was started with -S and
555# site is imported later.
556if not sys.flags.no_site:
557 main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000558
Christian Heimes8dc226f2008-05-06 23:45:46 +0000559def _script():
560 help = """\
561 %s [--user-base] [--user-site]
562
563 Without arguments print some useful information
564 With arguments print the value of USER_BASE and/or USER_SITE separated
565 by '%s'.
566
567 Exit codes with --user-base or --user-site:
568 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000569 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000570 2 - uses site directory is disabled by super user
571 or for security reasons
572 >2 - unknown error
573 """
574 args = sys.argv[1:]
575 if not args:
Meador Inge9a7a8112013-04-13 20:29:49 -0500576 user_base = getuserbase()
577 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000578 print("sys.path = [")
579 for dir in sys.path:
580 print(" %r," % (dir,))
581 print("]")
Meador Inge9a7a8112013-04-13 20:29:49 -0500582 print("USER_BASE: %r (%s)" % (user_base,
583 "exists" if os.path.isdir(user_base) else "doesn't exist"))
584 print("USER_SITE: %r (%s)" % (user_site,
585 "exists" if os.path.isdir(user_site) else "doesn't exist"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000586 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
587 sys.exit(0)
588
589 buffer = []
590 if '--user-base' in args:
591 buffer.append(USER_BASE)
592 if '--user-site' in args:
593 buffer.append(USER_SITE)
594
595 if buffer:
596 print(os.pathsep.join(buffer))
597 if ENABLE_USER_SITE:
598 sys.exit(0)
599 elif ENABLE_USER_SITE is False:
600 sys.exit(1)
601 elif ENABLE_USER_SITE is None:
602 sys.exit(2)
603 else:
604 sys.exit(3)
605 else:
606 import textwrap
607 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
608 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000609
610if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000611 _script()