blob: 13e73364ae484aaf16ab5a5b8e61932b18293eae [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
61After these path manipulations, an attempt is made to import a module
Guido van Rossumf30bec71997-08-29 22:30:45 +000062named sitecustomize, which can perform arbitrary additional
63site-specific customizations. If this import fails with an
64ImportError exception, it is silently ignored.
Guido van Rossume57c96e1996-08-17 19:56:26 +000065
Guido van Rossume57c96e1996-08-17 19:56:26 +000066"""
67
Brett Cannon0096e262004-06-05 01:12:51 +000068import sys
69import os
Vinay Sajip7ded1f02012-05-26 03:45:29 +010070import re
Georg Brandl1a3284e2007-12-02 09:40:06 +000071import builtins
Guido van Rossume57c96e1996-08-17 19:56:26 +000072
Christian Heimes8dc226f2008-05-06 23:45:46 +000073# Prefixes for site-packages; add additional prefixes like /usr/local here
74PREFIXES = [sys.prefix, sys.exec_prefix]
75# Enable per user site-packages directory
76# set it to False to disable the feature or True to force the feature
77ENABLE_USER_SITE = None
Tarek Ziadé4a608c02009-08-20 21:28:05 +000078
Christian Heimes8dc226f2008-05-06 23:45:46 +000079# for distutils.commands.install
Tarek Ziadé4a608c02009-08-20 21:28:05 +000080# These values are initialized by the getuserbase() and getusersitepackages()
81# functions, through the main() function when Python starts.
Christian Heimes8dc226f2008-05-06 23:45:46 +000082USER_SITE = None
83USER_BASE = None
84
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000085
Fred Drake38cb9f12000-09-28 16:52:36 +000086def makepath(*paths):
Victor Stinnerb103a932010-10-12 22:23:23 +000087 dir = os.path.join(*paths)
88 try:
89 dir = os.path.abspath(dir)
90 except OSError:
91 pass
Fred Drake1fb5ce02001-07-02 16:55:42 +000092 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000093
Christian Heimes8dc226f2008-05-06 23:45:46 +000094
Barry Warsaw28a691b2010-04-17 00:19:56 +000095def abs_paths():
96 """Set all module __file__ and __cached__ attributes to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000097 for m in set(sys.modules.values()):
Brett Cannonfd074152012-04-14 14:10:13 -040098 if (getattr(getattr(m, '__loader__', None), '__module__', None) !=
99 '_frozen_importlib'):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000100 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +0000101 try:
102 m.__file__ = os.path.abspath(m.__file__)
Victor Stinnerb103a932010-10-12 22:23:23 +0000103 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000104 pass
105 try:
106 m.__cached__ = os.path.abspath(m.__cached__)
Victor Stinnerb103a932010-10-12 22:23:23 +0000107 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000108 pass
Fred Drake38cb9f12000-09-28 16:52:36 +0000109
Christian Heimes8dc226f2008-05-06 23:45:46 +0000110
Brett Cannon0096e262004-06-05 01:12:51 +0000111def removeduppaths():
112 """ Remove duplicate entries from sys.path along with making them
113 absolute"""
114 # This ensures that the initial path provided by the interpreter contains
115 # only absolute pathnames, even if we're running from the build directory.
116 L = []
117 known_paths = set()
118 for dir in sys.path:
119 # Filter out duplicate paths (on case-insensitive file systems also
120 # if they only differ in case); turn relative paths into absolute
121 # paths.
122 dir, dircase = makepath(dir)
123 if not dircase in known_paths:
124 L.append(dir)
125 known_paths.add(dircase)
126 sys.path[:] = L
127 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000128
Christian Heimes8dc226f2008-05-06 23:45:46 +0000129
Fred Drake7f5296e2001-07-20 20:06:17 +0000130def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000131 """Return a set containing all existing directory entries from sys.path"""
132 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000133 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000134 try:
135 if os.path.isdir(dir):
136 dir, dircase = makepath(dir)
137 d.add(dircase)
138 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000139 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000140 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000141
Christian Heimes8dc226f2008-05-06 23:45:46 +0000142
Brett Cannon0096e262004-06-05 01:12:51 +0000143def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000144 """Process a .pth file within the site-packages directory:
145 For each line in the file, either combine it with sitedir to a path
146 and add that to known_paths, or execute it if it starts with 'import '.
147 """
Brett Cannon0096e262004-06-05 01:12:51 +0000148 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000149 _init_pathinfo()
150 reset = 1
151 else:
152 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000153 fullname = os.path.join(sitedir, name)
154 try:
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200155 f = open(fullname, "r")
Brett Cannon0096e262004-06-05 01:12:51 +0000156 except IOError:
157 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000158 with f:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000159 for n, line in enumerate(f):
Brett Cannon0096e262004-06-05 01:12:51 +0000160 if line.startswith("#"):
161 continue
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000162 try:
163 if line.startswith(("import ", "import\t")):
164 exec(line)
165 continue
166 line = line.rstrip()
167 dir, dircase = makepath(sitedir, line)
168 if not dircase in known_paths and os.path.exists(dir):
169 sys.path.append(dir)
170 known_paths.add(dircase)
Florent Xicluna54540ec2011-11-04 08:29:17 +0100171 except Exception:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000172 print("Error processing line {:d} of {}:\n".format(n+1, fullname),
173 file=sys.stderr)
Victor Stinner65532112012-02-21 22:10:16 +0100174 import traceback
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000175 for record in traceback.format_exception(*sys.exc_info()):
176 for line in record.splitlines():
177 print(' '+line, file=sys.stderr)
178 print("\nRemainder of file ignored", file=sys.stderr)
179 break
Brett Cannon0096e262004-06-05 01:12:51 +0000180 if reset:
181 known_paths = None
182 return known_paths
183
Christian Heimes8dc226f2008-05-06 23:45:46 +0000184
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000185def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000186 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
187 'sitedir'"""
188 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000189 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000190 reset = 1
191 else:
192 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000193 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000194 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000195 sys.path.append(sitedir) # Add path component
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100196 known_paths.add(sitedircase)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000197 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000199 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000201 names = [name for name in names if name.endswith(".pth")]
202 for name in sorted(names):
203 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000204 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000205 known_paths = None
206 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000207
Christian Heimes8dc226f2008-05-06 23:45:46 +0000208
209def check_enableusersite():
210 """Check if user site directory is safe for inclusion
211
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000212 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000213 process uid/gid equal to effective uid/gid.
214
215 None: Disabled for security reasons
216 False: Disabled by user (command line option)
217 True: Safe and enabled
218 """
219 if sys.flags.no_user_site:
220 return False
221
222 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
223 # check process uid == effective uid
224 if os.geteuid() != os.getuid():
225 return None
226 if hasattr(os, "getgid") and hasattr(os, "getegid"):
227 # check process gid == effective gid
228 if os.getegid() != os.getgid():
229 return None
230
231 return True
232
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000233def getuserbase():
234 """Returns the `user base` directory path.
235
236 The `user base` directory can be used to store data. If the global
237 variable ``USER_BASE`` is not initialized yet, this function will also set
238 it.
239 """
240 global USER_BASE
241 if USER_BASE is not None:
242 return USER_BASE
Tarek Ziadéedacea32010-01-29 11:41:03 +0000243 from sysconfig import get_config_var
244 USER_BASE = get_config_var('userbase')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000245 return USER_BASE
246
247def getusersitepackages():
248 """Returns the user-specific site-packages directory path.
249
250 If the global variable ``USER_SITE`` is not initialized yet, this
251 function will also set it.
252 """
253 global USER_SITE
254 user_base = getuserbase() # this will also set USER_BASE
255
256 if USER_SITE is not None:
257 return USER_SITE
258
Tarek Ziadéedacea32010-01-29 11:41:03 +0000259 from sysconfig import get_path
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000260
261 if sys.platform == 'darwin':
262 from sysconfig import get_config_var
263 if get_config_var('PYTHONFRAMEWORK'):
264 USER_SITE = get_path('purelib', 'osx_framework_user')
265 return USER_SITE
266
Tarek Ziadéedacea32010-01-29 11:41:03 +0000267 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000268 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000269
270def addusersitepackages(known_paths):
271 """Add a per user site-package to sys.path
272
273 Each user has its own python directory with site-packages in the
274 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000275 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000276 # get the per user site-package path
277 # this call will also make sure USER_BASE and USER_SITE are set
278 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000279
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000280 if ENABLE_USER_SITE and os.path.isdir(user_site):
281 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000282 return known_paths
283
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100284def getsitepackages(prefixes=None):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000285 """Returns a list containing all global site-packages directories
286 (and possibly site-python).
Christian Heimes8dc226f2008-05-06 23:45:46 +0000287
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100288 For each directory present in ``prefixes`` (or the global ``PREFIXES``),
289 this function will find its `site-packages` subdirectory depending on the
290 system environment, and will return a list of full paths.
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000291 """
292 sitepackages = []
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000293 seen = set()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000294
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100295 if prefixes is None:
296 prefixes = PREFIXES
297
298 for prefix in prefixes:
Christian Heimes8dc226f2008-05-06 23:45:46 +0000299 if not prefix or prefix in seen:
300 continue
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000301 seen.add(prefix)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000302
303 if sys.platform in ('os2emx', 'riscos'):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000304 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000305 elif os.sep == '/':
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000306 sitepackages.append(os.path.join(prefix, "lib",
Christian Heimes8dc226f2008-05-06 23:45:46 +0000307 "python" + sys.version[:3],
308 "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000309 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
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,
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000321 sys.version[:3], "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):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000325 """Add site-packages (and possibly site-python) 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 setBEGINLIBPATH():
333 """The OS/2 EMX port has optional extension modules that do double duty
334 as DLLs (and must use the .DLL file extension) for other extensions.
335 The library search path needs to be amended so these will be found
336 during module import. Use BEGINLIBPATH so that these are at the start
337 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000338
Brett Cannon0096e262004-06-05 01:12:51 +0000339 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000340 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
341 libpath = os.environ['BEGINLIBPATH'].split(';')
342 if libpath[-1]:
343 libpath.append(dllpath)
344 else:
345 libpath[-1] = dllpath
346 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
347
348
Brett Cannon0096e262004-06-05 01:12:51 +0000349def setquit():
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000350 """Define new builtins 'quit' and 'exit'.
351
352 These are objects which make the interpreter exit when called.
353 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000354
Brett Cannon0096e262004-06-05 01:12:51 +0000355 """
356 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000357 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000358 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000359 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000360 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000361 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000362
Georg Brandl24cb0532006-03-09 23:22:06 +0000363 class Quitter(object):
364 def __init__(self, name):
365 self.name = name
366 def __repr__(self):
367 return 'Use %s() or %s to exit' % (self.name, eof)
368 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000369 # Shells like IDLE catch the SystemExit, but listen when their
370 # stdin wrapper is closed.
371 try:
Roger Serwy1eafd102013-04-11 19:16:44 -0500372 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000373 except:
374 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000375 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000376 builtins.quit = Quitter('quit')
377 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000378
379
380class _Printer(object):
381 """interactive prompt objects for printing the license text, a list of
382 contributors and the copyright notice."""
383
Guido van Rossumd1252392000-09-05 04:39:55 +0000384 MAXLINES = 23
385
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000386 def __init__(self, name, data, files=(), dirs=()):
387 self.__name = name
388 self.__data = data
389 self.__files = files
390 self.__dirs = dirs
391 self.__lines = None
392
393 def __setup(self):
394 if self.__lines:
395 return
396 data = None
397 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000398 for filename in self.__files:
399 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000400 try:
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200401 fp = open(filename, "r")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000402 data = fp.read()
403 fp.close()
404 break
405 except IOError:
406 pass
407 if data:
408 break
409 if not data:
410 data = self.__data
411 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000412 self.__linecnt = len(self.__lines)
413
414 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000415 self.__setup()
416 if len(self.__lines) <= self.MAXLINES:
417 return "\n".join(self.__lines)
418 else:
419 return "Type %s() to see the full %s text" % ((self.__name,)*2)
420
421 def __call__(self):
422 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000423 prompt = 'Hit Return for more, or q (and Return) to quit: '
424 lineno = 0
425 while 1:
426 try:
427 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000428 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000429 except IndexError:
430 break
431 else:
432 lineno += self.MAXLINES
433 key = None
434 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000435 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000436 if key not in ('', 'q'):
437 key = None
438 if key == 'q':
439 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000440
Brett Cannon0096e262004-06-05 01:12:51 +0000441def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000442 """Set 'copyright' and 'credits' in builtins"""
443 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000444 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000445 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000446 "credits",
447 "Jython is maintained by the Jython developers (www.jython.org).")
448 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000449 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000450 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
451 for supporting Python development. See www.python.org for more information.""")
452 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000453 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000454 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
455 ["LICENSE.txt", "LICENSE"],
456 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000457
458
Brett Cannon0096e262004-06-05 01:12:51 +0000459class _Helper(object):
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000460 """Define the builtin 'help'.
Brett Cannon0096e262004-06-05 01:12:51 +0000461 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000462
Brett Cannon0096e262004-06-05 01:12:51 +0000463 """
464
Guido van Rossum83213cc2001-06-12 16:48:52 +0000465 def __repr__(self):
466 return "Type help() for interactive help, " \
467 "or help(object) for help about object."
468 def __call__(self, *args, **kwds):
469 import pydoc
470 return pydoc.help(*args, **kwds)
471
Brett Cannon0096e262004-06-05 01:12:51 +0000472def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000473 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000474
475def aliasmbcs():
476 """On Windows, some default encodings are not provided by Python,
477 while they are always available as "mbcs" in each locale. Make
478 them usable by aliasing to "mbcs" in such a case."""
479 if sys.platform == 'win32':
480 import locale, codecs
481 enc = locale.getdefaultlocale()[1]
482 if enc.startswith('cp'): # "cp***" ?
483 try:
484 codecs.lookup(enc)
485 except LookupError:
486 import encodings
487 encodings._cache[enc] = encodings._unknown
488 encodings.aliases.aliases[enc] = 'mbcs'
489
Guido van Rossum83213cc2001-06-12 16:48:52 +0000490
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100491CONFIG_LINE = re.compile(r'^(?P<key>(\w|[-_])+)\s*=\s*(?P<value>.*)\s*$')
492
493def venv(known_paths):
494 global PREFIXES, ENABLE_USER_SITE
495
496 env = os.environ
Vinay Sajip28952442012-06-25 00:47:46 +0100497 if sys.platform == 'darwin' and '__PYVENV_LAUNCHER__' in env:
498 executable = os.environ['__PYVENV_LAUNCHER__']
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100499 else:
500 executable = sys.executable
Vinay Sajip27e4b602012-11-23 19:16:49 +0000501 exe_dir, _ = os.path.split(os.path.abspath(executable))
502 site_prefix = os.path.dirname(exe_dir)
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100503 sys._home = None
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100504 conf_basename = 'pyvenv.cfg'
505 candidate_confs = [
506 conffile for conffile in (
Vinay Sajip27e4b602012-11-23 19:16:49 +0000507 os.path.join(exe_dir, conf_basename),
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100508 os.path.join(site_prefix, conf_basename)
509 )
510 if os.path.isfile(conffile)
511 ]
512
513 if candidate_confs:
514 virtual_conf = candidate_confs[0]
515 system_site = "true"
516 with open(virtual_conf) as f:
517 for line in f:
518 line = line.strip()
519 m = CONFIG_LINE.match(line)
520 if m:
521 d = m.groupdict()
522 key, value = d['key'].lower(), d['value']
523 if key == 'include-system-site-packages':
524 system_site = value.lower()
525 elif key == 'home':
526 sys._home = value
527
528 sys.prefix = sys.exec_prefix = site_prefix
529
530 # Doing this here ensures venv takes precedence over user-site
531 addsitepackages(known_paths, [sys.prefix])
532
533 # addsitepackages will process site_prefix again if its in PREFIXES,
534 # but that's ok; known_paths will prevent anything being added twice
535 if system_site == "true":
536 PREFIXES.insert(0, sys.prefix)
537 else:
538 PREFIXES = [sys.prefix]
539 ENABLE_USER_SITE = False
540
541 return known_paths
542
543
Brett Cannon0096e262004-06-05 01:12:51 +0000544def execsitecustomize():
545 """Run custom site specific code, if available."""
546 try:
547 import sitecustomize
548 except ImportError:
549 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000550 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000551 if os.environ.get("PYTHONVERBOSE"):
Victor Stinner52f6dd72010-03-12 14:45:56 +0000552 sys.excepthook(*sys.exc_info())
553 else:
554 sys.stderr.write(
555 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
556 "%s: %s\n" %
557 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000558
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000559
Christian Heimes8dc226f2008-05-06 23:45:46 +0000560def execusercustomize():
561 """Run custom user specific code, if available."""
562 try:
563 import usercustomize
564 except ImportError:
565 pass
Victor Stinner52f6dd72010-03-12 14:45:56 +0000566 except Exception as err:
567 if os.environ.get("PYTHONVERBOSE"):
568 sys.excepthook(*sys.exc_info())
569 else:
570 sys.stderr.write(
571 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
572 "%s: %s\n" %
573 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000574
575
Brett Cannon0096e262004-06-05 01:12:51 +0000576def main():
Éric Araujoc09fca62011-03-23 02:06:24 +0100577 """Add standard site-specific directories to the module search path.
578
579 This function is called automatically when this module is imported,
580 unless the python interpreter was started with the -S flag.
581 """
Christian Heimes8dc226f2008-05-06 23:45:46 +0000582 global ENABLE_USER_SITE
583
Barry Warsaw28a691b2010-04-17 00:19:56 +0000584 abs_paths()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000585 known_paths = removeduppaths()
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100586 known_paths = venv(known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000587 if ENABLE_USER_SITE is None:
588 ENABLE_USER_SITE = check_enableusersite()
589 known_paths = addusersitepackages(known_paths)
590 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000591 if sys.platform == 'os2emx':
592 setBEGINLIBPATH()
593 setquit()
594 setcopyright()
595 sethelper()
596 aliasmbcs()
Brett Cannon0096e262004-06-05 01:12:51 +0000597 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000598 if ENABLE_USER_SITE:
599 execusercustomize()
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000600
Éric Araujoc09fca62011-03-23 02:06:24 +0100601# Prevent edition of sys.path when python was started with -S and
602# site is imported later.
603if not sys.flags.no_site:
604 main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000605
Christian Heimes8dc226f2008-05-06 23:45:46 +0000606def _script():
607 help = """\
608 %s [--user-base] [--user-site]
609
610 Without arguments print some useful information
611 With arguments print the value of USER_BASE and/or USER_SITE separated
612 by '%s'.
613
614 Exit codes with --user-base or --user-site:
615 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000616 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000617 2 - uses site directory is disabled by super user
618 or for security reasons
619 >2 - unknown error
620 """
621 args = sys.argv[1:]
622 if not args:
Meador Inge9a7a8112013-04-13 20:29:49 -0500623 user_base = getuserbase()
624 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000625 print("sys.path = [")
626 for dir in sys.path:
627 print(" %r," % (dir,))
628 print("]")
Meador Inge9a7a8112013-04-13 20:29:49 -0500629 print("USER_BASE: %r (%s)" % (user_base,
630 "exists" if os.path.isdir(user_base) else "doesn't exist"))
631 print("USER_SITE: %r (%s)" % (user_site,
632 "exists" if os.path.isdir(user_site) else "doesn't exist"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000633 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
634 sys.exit(0)
635
636 buffer = []
637 if '--user-base' in args:
638 buffer.append(USER_BASE)
639 if '--user-site' in args:
640 buffer.append(USER_SITE)
641
642 if buffer:
643 print(os.pathsep.join(buffer))
644 if ENABLE_USER_SITE:
645 sys.exit(0)
646 elif ENABLE_USER_SITE is False:
647 sys.exit(1)
648 elif ENABLE_USER_SITE is None:
649 sys.exit(2)
650 else:
651 sys.exit(3)
652 else:
653 import textwrap
654 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
655 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000656
657if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000658 _script()