blob: 9d1084a4a2e0cfd984f7bd6698aa976d34072f75 [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
Guido van Rossumf30bec71997-08-29 22:30:45 +000016A path configuration file is a file whose name has the form
17<package>.pth; its contents are additional directories (one per line)
18to be added to sys.path. Non-existing directories (or
19non-directories) are never added to sys.path; no directory is added to
20sys.path more than once. Blank lines and lines beginning with
Guido van Rossumfacf24b2001-12-17 16:07:06 +000021'#' are skipped. Lines starting with 'import' are executed.
Guido van Rossume57c96e1996-08-17 19:56:26 +000022
Guido van Rossumf30bec71997-08-29 22:30:45 +000023For example, suppose sys.prefix and sys.exec_prefix are set to
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000024/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
Guido van Rossum62b297b1997-09-08 02:14:09 +000025with three subdirectories, foo, bar and spam, and two path
26configuration files, foo.pth and bar.pth. Assume foo.pth contains the
27following:
Guido van Rossumf30bec71997-08-29 22:30:45 +000028
29 # foo package configuration
30 foo
31 bar
32 bletch
33
34and bar.pth contains:
35
36 # bar package configuration
37 bar
38
39Then the following directories are added to sys.path, in this order:
40
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000041 /usr/local/lib/python2.5/site-packages/bar
42 /usr/local/lib/python2.5/site-packages/foo
Guido van Rossumf30bec71997-08-29 22:30:45 +000043
44Note that bletch is omitted because it doesn't exist; bar precedes foo
45because bar.pth comes alphabetically before foo.pth; and spam is
46omitted because it is not mentioned in either path configuration file.
Guido van Rossume57c96e1996-08-17 19:56:26 +000047
48After these path manipulations, an attempt is made to import a module
Guido van Rossumf30bec71997-08-29 22:30:45 +000049named sitecustomize, which can perform arbitrary additional
50site-specific customizations. If this import fails with an
51ImportError exception, it is silently ignored.
Guido van Rossume57c96e1996-08-17 19:56:26 +000052
Guido van Rossume57c96e1996-08-17 19:56:26 +000053"""
54
Brett Cannon0096e262004-06-05 01:12:51 +000055import sys
56import os
Georg Brandl1a3284e2007-12-02 09:40:06 +000057import builtins
Guido van Rossume57c96e1996-08-17 19:56:26 +000058
Christian Heimes8dc226f2008-05-06 23:45:46 +000059# Prefixes for site-packages; add additional prefixes like /usr/local here
60PREFIXES = [sys.prefix, sys.exec_prefix]
61# Enable per user site-packages directory
62# set it to False to disable the feature or True to force the feature
63ENABLE_USER_SITE = None
Tarek Ziadé4a608c02009-08-20 21:28:05 +000064
Christian Heimes8dc226f2008-05-06 23:45:46 +000065# for distutils.commands.install
Tarek Ziadé4a608c02009-08-20 21:28:05 +000066# These values are initialized by the getuserbase() and getusersitepackages()
67# functions, through the main() function when Python starts.
Christian Heimes8dc226f2008-05-06 23:45:46 +000068USER_SITE = None
69USER_BASE = None
70
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000071
Fred Drake38cb9f12000-09-28 16:52:36 +000072def makepath(*paths):
Victor Stinnerb103a932010-10-12 22:23:23 +000073 dir = os.path.join(*paths)
74 try:
75 dir = os.path.abspath(dir)
76 except OSError:
77 pass
Fred Drake1fb5ce02001-07-02 16:55:42 +000078 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000079
Christian Heimes8dc226f2008-05-06 23:45:46 +000080
Barry Warsaw28a691b2010-04-17 00:19:56 +000081def abs_paths():
82 """Set all module __file__ and __cached__ attributes to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000083 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000084 if hasattr(m, '__loader__'):
85 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000086 try:
87 m.__file__ = os.path.abspath(m.__file__)
Victor Stinnerb103a932010-10-12 22:23:23 +000088 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +000089 pass
90 try:
91 m.__cached__ = os.path.abspath(m.__cached__)
Victor Stinnerb103a932010-10-12 22:23:23 +000092 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +000093 pass
Fred Drake38cb9f12000-09-28 16:52:36 +000094
Christian Heimes8dc226f2008-05-06 23:45:46 +000095
Brett Cannon0096e262004-06-05 01:12:51 +000096def removeduppaths():
97 """ Remove duplicate entries from sys.path along with making them
98 absolute"""
99 # This ensures that the initial path provided by the interpreter contains
100 # only absolute pathnames, even if we're running from the build directory.
101 L = []
102 known_paths = set()
103 for dir in sys.path:
104 # Filter out duplicate paths (on case-insensitive file systems also
105 # if they only differ in case); turn relative paths into absolute
106 # paths.
107 dir, dircase = makepath(dir)
108 if not dircase in known_paths:
109 L.append(dir)
110 known_paths.add(dircase)
111 sys.path[:] = L
112 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000113
Christian Heimes8dc226f2008-05-06 23:45:46 +0000114
Fred Drake7f5296e2001-07-20 20:06:17 +0000115def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000116 """Return a set containing all existing directory entries from sys.path"""
117 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000118 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000119 try:
120 if os.path.isdir(dir):
121 dir, dircase = makepath(dir)
122 d.add(dircase)
123 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000124 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000125 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000126
Christian Heimes8dc226f2008-05-06 23:45:46 +0000127
Brett Cannon0096e262004-06-05 01:12:51 +0000128def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000129 """Process a .pth file within the site-packages directory:
130 For each line in the file, either combine it with sitedir to a path
131 and add that to known_paths, or execute it if it starts with 'import '.
132 """
Brett Cannon0096e262004-06-05 01:12:51 +0000133 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000134 _init_pathinfo()
135 reset = 1
136 else:
137 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000138 fullname = os.path.join(sitedir, name)
139 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000140 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000141 except IOError:
142 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000143 with f:
Brett Cannon0096e262004-06-05 01:12:51 +0000144 for line in f:
145 if line.startswith("#"):
146 continue
Christian Heimes8dc226f2008-05-06 23:45:46 +0000147 if line.startswith(("import ", "import\t")):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000148 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000149 continue
150 line = line.rstrip()
151 dir, dircase = makepath(sitedir, line)
152 if not dircase in known_paths and os.path.exists(dir):
153 sys.path.append(dir)
154 known_paths.add(dircase)
Brett Cannon0096e262004-06-05 01:12:51 +0000155 if reset:
156 known_paths = None
157 return known_paths
158
Christian Heimes8dc226f2008-05-06 23:45:46 +0000159
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000160def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000161 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
162 'sitedir'"""
163 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000164 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000165 reset = 1
166 else:
167 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000168 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000169 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000171 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000172 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000173 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000175 names = [name for name in names if name.endswith(".pth")]
176 for name in sorted(names):
177 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000178 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000179 known_paths = None
180 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000181
Christian Heimes8dc226f2008-05-06 23:45:46 +0000182
183def check_enableusersite():
184 """Check if user site directory is safe for inclusion
185
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000186 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000187 process uid/gid equal to effective uid/gid.
188
189 None: Disabled for security reasons
190 False: Disabled by user (command line option)
191 True: Safe and enabled
192 """
193 if sys.flags.no_user_site:
194 return False
195
196 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
197 # check process uid == effective uid
198 if os.geteuid() != os.getuid():
199 return None
200 if hasattr(os, "getgid") and hasattr(os, "getegid"):
201 # check process gid == effective gid
202 if os.getegid() != os.getgid():
203 return None
204
205 return True
206
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000207def getuserbase():
208 """Returns the `user base` directory path.
209
210 The `user base` directory can be used to store data. If the global
211 variable ``USER_BASE`` is not initialized yet, this function will also set
212 it.
213 """
214 global USER_BASE
215 if USER_BASE is not None:
216 return USER_BASE
Tarek Ziadéedacea32010-01-29 11:41:03 +0000217 from sysconfig import get_config_var
218 USER_BASE = get_config_var('userbase')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000219 return USER_BASE
220
221def getusersitepackages():
222 """Returns the user-specific site-packages directory path.
223
224 If the global variable ``USER_SITE`` is not initialized yet, this
225 function will also set it.
226 """
227 global USER_SITE
228 user_base = getuserbase() # this will also set USER_BASE
229
230 if USER_SITE is not None:
231 return USER_SITE
232
Tarek Ziadéedacea32010-01-29 11:41:03 +0000233 from sysconfig import get_path
234 import os
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000235
236 if sys.platform == 'darwin':
237 from sysconfig import get_config_var
238 if get_config_var('PYTHONFRAMEWORK'):
239 USER_SITE = get_path('purelib', 'osx_framework_user')
240 return USER_SITE
241
Tarek Ziadéedacea32010-01-29 11:41:03 +0000242 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000243 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000244
245def addusersitepackages(known_paths):
246 """Add a per user site-package to sys.path
247
248 Each user has its own python directory with site-packages in the
249 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000250 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000251 # get the per user site-package path
252 # this call will also make sure USER_BASE and USER_SITE are set
253 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000254
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000255 if ENABLE_USER_SITE and os.path.isdir(user_site):
256 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000257 return known_paths
258
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000259def getsitepackages():
260 """Returns a list containing all global site-packages directories
261 (and possibly site-python).
Christian Heimes8dc226f2008-05-06 23:45:46 +0000262
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000263 For each directory present in the global ``PREFIXES``, this function
264 will find its `site-packages` subdirectory depending on the system
265 environment, and will return a list of full paths.
266 """
267 sitepackages = []
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000268 seen = set()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000269
270 for prefix in PREFIXES:
271 if not prefix or prefix in seen:
272 continue
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000273 seen.add(prefix)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000274
275 if sys.platform in ('os2emx', 'riscos'):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000276 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000277 elif os.sep == '/':
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000278 sitepackages.append(os.path.join(prefix, "lib",
Christian Heimes8dc226f2008-05-06 23:45:46 +0000279 "python" + sys.version[:3],
280 "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000281 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000282 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000283 sitepackages.append(prefix)
284 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000285 if sys.platform == "darwin":
286 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000287 # locations.
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000288 from sysconfig import get_config_var
289 framework = get_config_var("PYTHONFRAMEWORK")
Ronald Oussorenbda46722010-08-01 09:02:50 +0000290 if framework:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000291 sitepackages.append(
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000292 os.path.join("/Library", framework,
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000293 sys.version[:3], "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000294 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000295
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000296def addsitepackages(known_paths):
297 """Add site-packages (and possibly site-python) to sys.path"""
298 for sitedir in getsitepackages():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000299 if os.path.isdir(sitedir):
300 addsitedir(sitedir, known_paths)
301
302 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000303
Brett Cannon0096e262004-06-05 01:12:51 +0000304def setBEGINLIBPATH():
305 """The OS/2 EMX port has optional extension modules that do double duty
306 as DLLs (and must use the .DLL file extension) for other extensions.
307 The library search path needs to be amended so these will be found
308 during module import. Use BEGINLIBPATH so that these are at the start
309 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000310
Brett Cannon0096e262004-06-05 01:12:51 +0000311 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000312 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
313 libpath = os.environ['BEGINLIBPATH'].split(';')
314 if libpath[-1]:
315 libpath.append(dllpath)
316 else:
317 libpath[-1] = dllpath
318 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
319
320
Brett Cannon0096e262004-06-05 01:12:51 +0000321def setquit():
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000322 """Define new builtins 'quit' and 'exit'.
323
324 These are objects which make the interpreter exit when called.
325 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000326
Brett Cannon0096e262004-06-05 01:12:51 +0000327 """
328 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000329 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000330 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000331 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000332 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000333 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000334
Georg Brandl24cb0532006-03-09 23:22:06 +0000335 class Quitter(object):
336 def __init__(self, name):
337 self.name = name
338 def __repr__(self):
339 return 'Use %s() or %s to exit' % (self.name, eof)
340 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000341 # Shells like IDLE catch the SystemExit, but listen when their
342 # stdin wrapper is closed.
343 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000344 fd = -1
345 if hasattr(sys.stdin, "fileno"):
346 fd = sys.stdin.fileno()
347 if fd != 0:
348 # Don't close stdin if it wraps fd 0
349 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000350 except:
351 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000352 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000353 builtins.quit = Quitter('quit')
354 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000355
356
357class _Printer(object):
358 """interactive prompt objects for printing the license text, a list of
359 contributors and the copyright notice."""
360
Guido van Rossumd1252392000-09-05 04:39:55 +0000361 MAXLINES = 23
362
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000363 def __init__(self, name, data, files=(), dirs=()):
364 self.__name = name
365 self.__data = data
366 self.__files = files
367 self.__dirs = dirs
368 self.__lines = None
369
370 def __setup(self):
371 if self.__lines:
372 return
373 data = None
374 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000375 for filename in self.__files:
376 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000377 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000378 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000379 data = fp.read()
380 fp.close()
381 break
382 except IOError:
383 pass
384 if data:
385 break
386 if not data:
387 data = self.__data
388 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000389 self.__linecnt = len(self.__lines)
390
391 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000392 self.__setup()
393 if len(self.__lines) <= self.MAXLINES:
394 return "\n".join(self.__lines)
395 else:
396 return "Type %s() to see the full %s text" % ((self.__name,)*2)
397
398 def __call__(self):
399 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000400 prompt = 'Hit Return for more, or q (and Return) to quit: '
401 lineno = 0
402 while 1:
403 try:
404 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000405 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000406 except IndexError:
407 break
408 else:
409 lineno += self.MAXLINES
410 key = None
411 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000412 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000413 if key not in ('', 'q'):
414 key = None
415 if key == 'q':
416 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000417
Brett Cannon0096e262004-06-05 01:12:51 +0000418def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000419 """Set 'copyright' and 'credits' in builtins"""
420 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000421 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000422 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000423 "credits",
424 "Jython is maintained by the Jython developers (www.jython.org).")
425 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000426 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000427 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
428 for supporting Python development. See www.python.org for more information.""")
429 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000430 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000431 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
432 ["LICENSE.txt", "LICENSE"],
433 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000434
435
Brett Cannon0096e262004-06-05 01:12:51 +0000436class _Helper(object):
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000437 """Define the builtin 'help'.
Brett Cannon0096e262004-06-05 01:12:51 +0000438 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000439
Brett Cannon0096e262004-06-05 01:12:51 +0000440 """
441
Guido van Rossum83213cc2001-06-12 16:48:52 +0000442 def __repr__(self):
443 return "Type help() for interactive help, " \
444 "or help(object) for help about object."
445 def __call__(self, *args, **kwds):
446 import pydoc
447 return pydoc.help(*args, **kwds)
448
Brett Cannon0096e262004-06-05 01:12:51 +0000449def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000450 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000451
452def aliasmbcs():
453 """On Windows, some default encodings are not provided by Python,
454 while they are always available as "mbcs" in each locale. Make
455 them usable by aliasing to "mbcs" in such a case."""
456 if sys.platform == 'win32':
457 import locale, codecs
458 enc = locale.getdefaultlocale()[1]
459 if enc.startswith('cp'): # "cp***" ?
460 try:
461 codecs.lookup(enc)
462 except LookupError:
463 import encodings
464 encodings._cache[enc] = encodings._unknown
465 encodings.aliases.aliases[enc] = 'mbcs'
466
Guido van Rossum83213cc2001-06-12 16:48:52 +0000467
Brett Cannon0096e262004-06-05 01:12:51 +0000468def execsitecustomize():
469 """Run custom site specific code, if available."""
470 try:
471 import sitecustomize
472 except ImportError:
473 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000474 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000475 if os.environ.get("PYTHONVERBOSE"):
Victor Stinner52f6dd72010-03-12 14:45:56 +0000476 sys.excepthook(*sys.exc_info())
477 else:
478 sys.stderr.write(
479 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
480 "%s: %s\n" %
481 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000482
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000483
Christian Heimes8dc226f2008-05-06 23:45:46 +0000484def execusercustomize():
485 """Run custom user specific code, if available."""
486 try:
487 import usercustomize
488 except ImportError:
489 pass
Victor Stinner52f6dd72010-03-12 14:45:56 +0000490 except Exception as err:
491 if os.environ.get("PYTHONVERBOSE"):
492 sys.excepthook(*sys.exc_info())
493 else:
494 sys.stderr.write(
495 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
496 "%s: %s\n" %
497 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000498
499
Brett Cannon0096e262004-06-05 01:12:51 +0000500def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000501 global ENABLE_USER_SITE
502
Barry Warsaw28a691b2010-04-17 00:19:56 +0000503 abs_paths()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000504 known_paths = removeduppaths()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000505 if ENABLE_USER_SITE is None:
506 ENABLE_USER_SITE = check_enableusersite()
507 known_paths = addusersitepackages(known_paths)
508 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000509 if sys.platform == 'os2emx':
510 setBEGINLIBPATH()
511 setquit()
512 setcopyright()
513 sethelper()
514 aliasmbcs()
Brett Cannon0096e262004-06-05 01:12:51 +0000515 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000516 if ENABLE_USER_SITE:
517 execusercustomize()
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000518
Brett Cannon0096e262004-06-05 01:12:51 +0000519main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000520
Christian Heimes8dc226f2008-05-06 23:45:46 +0000521def _script():
522 help = """\
523 %s [--user-base] [--user-site]
524
525 Without arguments print some useful information
526 With arguments print the value of USER_BASE and/or USER_SITE separated
527 by '%s'.
528
529 Exit codes with --user-base or --user-site:
530 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000531 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000532 2 - uses site directory is disabled by super user
533 or for security reasons
534 >2 - unknown error
535 """
536 args = sys.argv[1:]
537 if not args:
538 print("sys.path = [")
539 for dir in sys.path:
540 print(" %r," % (dir,))
541 print("]")
542 print("USER_BASE: %r (%s)" % (USER_BASE,
543 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
544 print("USER_SITE: %r (%s)" % (USER_SITE,
545 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
546 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
547 sys.exit(0)
548
549 buffer = []
550 if '--user-base' in args:
551 buffer.append(USER_BASE)
552 if '--user-site' in args:
553 buffer.append(USER_SITE)
554
555 if buffer:
556 print(os.pathsep.join(buffer))
557 if ENABLE_USER_SITE:
558 sys.exit(0)
559 elif ENABLE_USER_SITE is False:
560 sys.exit(1)
561 elif ENABLE_USER_SITE is None:
562 sys.exit(2)
563 else:
564 sys.exit(3)
565 else:
566 import textwrap
567 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
568 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000569
570if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000571 _script()