blob: bf4d67f0d2a08fed67a6dce284a35fb3ab8a3321 [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):
Fred Drake1fb5ce02001-07-02 16:55:42 +000073 dir = os.path.abspath(os.path.join(*paths))
74 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000075
Christian Heimes8dc226f2008-05-06 23:45:46 +000076
Brett Cannon0096e262004-06-05 01:12:51 +000077def abs__file__():
78 """Set all module' __file__ attribute to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000079 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000080 if hasattr(m, '__loader__'):
81 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000082 try:
83 m.__file__ = os.path.abspath(m.__file__)
84 except AttributeError:
85 continue
Fred Drake38cb9f12000-09-28 16:52:36 +000086
Christian Heimes8dc226f2008-05-06 23:45:46 +000087
Brett Cannon0096e262004-06-05 01:12:51 +000088def removeduppaths():
89 """ Remove duplicate entries from sys.path along with making them
90 absolute"""
91 # This ensures that the initial path provided by the interpreter contains
92 # only absolute pathnames, even if we're running from the build directory.
93 L = []
94 known_paths = set()
95 for dir in sys.path:
96 # Filter out duplicate paths (on case-insensitive file systems also
97 # if they only differ in case); turn relative paths into absolute
98 # paths.
99 dir, dircase = makepath(dir)
100 if not dircase in known_paths:
101 L.append(dir)
102 known_paths.add(dircase)
103 sys.path[:] = L
104 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000105
Fred Drakee80c0d32002-07-25 20:13:03 +0000106# XXX This should not be part of site.py, since it is needed even when
107# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000108def addbuilddir():
109 """Append ./build/lib.<platform> in case we're running in the build dir
110 (especially for Guido :-)"""
Tarek Ziadéedacea32010-01-29 11:41:03 +0000111 from sysconfig import get_platform
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000112 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Christian Heimes1af737c2008-01-23 08:24:23 +0000113 if hasattr(sys, 'gettotalrefcount'):
114 s += '-pydebug'
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000115 s = os.path.join(os.path.dirname(sys.path[-1]), s)
116 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000117
Christian Heimes8dc226f2008-05-06 23:45:46 +0000118
Fred Drake7f5296e2001-07-20 20:06:17 +0000119def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000120 """Return a set containing all existing directory entries from sys.path"""
121 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000122 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000123 try:
124 if os.path.isdir(dir):
125 dir, dircase = makepath(dir)
126 d.add(dircase)
127 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000128 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000129 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000130
Christian Heimes8dc226f2008-05-06 23:45:46 +0000131
Brett Cannon0096e262004-06-05 01:12:51 +0000132def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000133 """Process a .pth file within the site-packages directory:
134 For each line in the file, either combine it with sitedir to a path
135 and add that to known_paths, or execute it if it starts with 'import '.
136 """
Brett Cannon0096e262004-06-05 01:12:51 +0000137 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000138 _init_pathinfo()
139 reset = 1
140 else:
141 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000142 fullname = os.path.join(sitedir, name)
143 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000144 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000145 except IOError:
146 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000147 with f:
Brett Cannon0096e262004-06-05 01:12:51 +0000148 for line in f:
149 if line.startswith("#"):
150 continue
Christian Heimes8dc226f2008-05-06 23:45:46 +0000151 if line.startswith(("import ", "import\t")):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000152 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000153 continue
154 line = line.rstrip()
155 dir, dircase = makepath(sitedir, line)
156 if not dircase in known_paths and os.path.exists(dir):
157 sys.path.append(dir)
158 known_paths.add(dircase)
Brett Cannon0096e262004-06-05 01:12:51 +0000159 if reset:
160 known_paths = None
161 return known_paths
162
Christian Heimes8dc226f2008-05-06 23:45:46 +0000163
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000164def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000165 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
166 'sitedir'"""
167 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000168 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000169 reset = 1
170 else:
171 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000172 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000173 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000175 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000176 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000177 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000179 names = [name for name in names if name.endswith(".pth")]
180 for name in sorted(names):
181 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000182 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000183 known_paths = None
184 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000185
Christian Heimes8dc226f2008-05-06 23:45:46 +0000186
187def check_enableusersite():
188 """Check if user site directory is safe for inclusion
189
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000190 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000191 process uid/gid equal to effective uid/gid.
192
193 None: Disabled for security reasons
194 False: Disabled by user (command line option)
195 True: Safe and enabled
196 """
197 if sys.flags.no_user_site:
198 return False
199
200 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
201 # check process uid == effective uid
202 if os.geteuid() != os.getuid():
203 return None
204 if hasattr(os, "getgid") and hasattr(os, "getegid"):
205 # check process gid == effective gid
206 if os.getegid() != os.getgid():
207 return None
208
209 return True
210
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000211def getuserbase():
212 """Returns the `user base` directory path.
213
214 The `user base` directory can be used to store data. If the global
215 variable ``USER_BASE`` is not initialized yet, this function will also set
216 it.
217 """
218 global USER_BASE
219 if USER_BASE is not None:
220 return USER_BASE
Tarek Ziadéedacea32010-01-29 11:41:03 +0000221 from sysconfig import get_config_var
222 USER_BASE = get_config_var('userbase')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000223 return USER_BASE
224
225def getusersitepackages():
226 """Returns the user-specific site-packages directory path.
227
228 If the global variable ``USER_SITE`` is not initialized yet, this
229 function will also set it.
230 """
231 global USER_SITE
232 user_base = getuserbase() # this will also set USER_BASE
233
234 if USER_SITE is not None:
235 return USER_SITE
236
Tarek Ziadéedacea32010-01-29 11:41:03 +0000237 from sysconfig import get_path
238 import os
239 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000240 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000241
242def addusersitepackages(known_paths):
243 """Add a per user site-package to sys.path
244
245 Each user has its own python directory with site-packages in the
246 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000247 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000248 # get the per user site-package path
249 # this call will also make sure USER_BASE and USER_SITE are set
250 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000251
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000252 if ENABLE_USER_SITE and os.path.isdir(user_site):
253 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000254 return known_paths
255
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000256def getsitepackages():
257 """Returns a list containing all global site-packages directories
258 (and possibly site-python).
Christian Heimes8dc226f2008-05-06 23:45:46 +0000259
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000260 For each directory present in the global ``PREFIXES``, this function
261 will find its `site-packages` subdirectory depending on the system
262 environment, and will return a list of full paths.
263 """
264 sitepackages = []
Christian Heimes8dc226f2008-05-06 23:45:46 +0000265 seen = []
266
267 for prefix in PREFIXES:
268 if not prefix or prefix in seen:
269 continue
270 seen.append(prefix)
271
272 if sys.platform in ('os2emx', 'riscos'):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000273 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000274 elif os.sep == '/':
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000275 sitepackages.append(os.path.join(prefix, "lib",
Christian Heimes8dc226f2008-05-06 23:45:46 +0000276 "python" + sys.version[:3],
277 "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000278 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000279 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000280 sitepackages.append(prefix)
281 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000282 if sys.platform == "darwin":
283 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000284 # locations.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000285 if 'Python.framework' in prefix:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000286 sitepackages.append(
Christian Heimes8dc226f2008-05-06 23:45:46 +0000287 os.path.expanduser(
288 os.path.join("~", "Library", "Python",
289 sys.version[:3], "site-packages")))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000290 sitepackages.append(
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000291 os.path.join("/Library", "Python",
292 sys.version[:3], "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000293 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000294
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000295def addsitepackages(known_paths):
296 """Add site-packages (and possibly site-python) to sys.path"""
297 for sitedir in getsitepackages():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000298 if os.path.isdir(sitedir):
299 addsitedir(sitedir, known_paths)
300
301 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000302
Brett Cannon0096e262004-06-05 01:12:51 +0000303def setBEGINLIBPATH():
304 """The OS/2 EMX port has optional extension modules that do double duty
305 as DLLs (and must use the .DLL file extension) for other extensions.
306 The library search path needs to be amended so these will be found
307 during module import. Use BEGINLIBPATH so that these are at the start
308 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000309
Brett Cannon0096e262004-06-05 01:12:51 +0000310 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000311 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
312 libpath = os.environ['BEGINLIBPATH'].split(';')
313 if libpath[-1]:
314 libpath.append(dllpath)
315 else:
316 libpath[-1] = dllpath
317 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
318
319
Brett Cannon0096e262004-06-05 01:12:51 +0000320def setquit():
321 """Define new built-ins 'quit' and 'exit'.
322 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000323
Brett Cannon0096e262004-06-05 01:12:51 +0000324 """
325 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000326 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000327 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000328 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000329 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000330 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000331
Georg Brandl24cb0532006-03-09 23:22:06 +0000332 class Quitter(object):
333 def __init__(self, name):
334 self.name = name
335 def __repr__(self):
336 return 'Use %s() or %s to exit' % (self.name, eof)
337 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000338 # Shells like IDLE catch the SystemExit, but listen when their
339 # stdin wrapper is closed.
340 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000341 fd = -1
342 if hasattr(sys.stdin, "fileno"):
343 fd = sys.stdin.fileno()
344 if fd != 0:
345 # Don't close stdin if it wraps fd 0
346 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000347 except:
348 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000349 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000350 builtins.quit = Quitter('quit')
351 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000352
353
354class _Printer(object):
355 """interactive prompt objects for printing the license text, a list of
356 contributors and the copyright notice."""
357
Guido van Rossumd1252392000-09-05 04:39:55 +0000358 MAXLINES = 23
359
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000360 def __init__(self, name, data, files=(), dirs=()):
361 self.__name = name
362 self.__data = data
363 self.__files = files
364 self.__dirs = dirs
365 self.__lines = None
366
367 def __setup(self):
368 if self.__lines:
369 return
370 data = None
371 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000372 for filename in self.__files:
373 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000374 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000375 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000376 data = fp.read()
377 fp.close()
378 break
379 except IOError:
380 pass
381 if data:
382 break
383 if not data:
384 data = self.__data
385 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000386 self.__linecnt = len(self.__lines)
387
388 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000389 self.__setup()
390 if len(self.__lines) <= self.MAXLINES:
391 return "\n".join(self.__lines)
392 else:
393 return "Type %s() to see the full %s text" % ((self.__name,)*2)
394
395 def __call__(self):
396 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000397 prompt = 'Hit Return for more, or q (and Return) to quit: '
398 lineno = 0
399 while 1:
400 try:
401 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000402 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000403 except IndexError:
404 break
405 else:
406 lineno += self.MAXLINES
407 key = None
408 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000409 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000410 if key not in ('', 'q'):
411 key = None
412 if key == 'q':
413 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000414
Brett Cannon0096e262004-06-05 01:12:51 +0000415def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000416 """Set 'copyright' and 'credits' in builtins"""
417 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000418 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000419 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000420 "credits",
421 "Jython is maintained by the Jython developers (www.jython.org).")
422 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000423 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000424 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
425 for supporting Python development. See www.python.org for more information.""")
426 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000427 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000428 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
429 ["LICENSE.txt", "LICENSE"],
430 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000431
432
Brett Cannon0096e262004-06-05 01:12:51 +0000433class _Helper(object):
434 """Define the built-in 'help'.
435 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000436
Brett Cannon0096e262004-06-05 01:12:51 +0000437 """
438
Guido van Rossum83213cc2001-06-12 16:48:52 +0000439 def __repr__(self):
440 return "Type help() for interactive help, " \
441 "or help(object) for help about object."
442 def __call__(self, *args, **kwds):
443 import pydoc
444 return pydoc.help(*args, **kwds)
445
Brett Cannon0096e262004-06-05 01:12:51 +0000446def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000447 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000448
449def aliasmbcs():
450 """On Windows, some default encodings are not provided by Python,
451 while they are always available as "mbcs" in each locale. Make
452 them usable by aliasing to "mbcs" in such a case."""
453 if sys.platform == 'win32':
454 import locale, codecs
455 enc = locale.getdefaultlocale()[1]
456 if enc.startswith('cp'): # "cp***" ?
457 try:
458 codecs.lookup(enc)
459 except LookupError:
460 import encodings
461 encodings._cache[enc] = encodings._unknown
462 encodings.aliases.aliases[enc] = 'mbcs'
463
464def setencoding():
465 """Set the string encoding used by the Unicode implementation. The
466 default is 'ascii', but if you're willing to experiment, you can
467 change this."""
468 encoding = "ascii" # Default value set by _PyUnicode_Init()
469 if 0:
470 # Enable to support locale aware default string encodings.
471 import locale
472 loc = locale.getdefaultlocale()
473 if loc[1]:
474 encoding = loc[1]
475 if 0:
476 # Enable to switch off string to Unicode coercion and implicit
477 # Unicode to string conversion.
478 encoding = "undefined"
479 if encoding != "ascii":
480 # On Non-Unicode builds this will raise an AttributeError...
481 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000482
483
Brett Cannon0096e262004-06-05 01:12:51 +0000484def execsitecustomize():
485 """Run custom site specific code, if available."""
486 try:
487 import sitecustomize
488 except ImportError:
489 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000490 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000491 if os.environ.get("PYTHONVERBOSE"):
492 raise
493 sys.stderr.write(
494 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
495 "%s: %s\n" %
496 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000497
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000498
Christian Heimes8dc226f2008-05-06 23:45:46 +0000499def execusercustomize():
500 """Run custom user specific code, if available."""
501 try:
502 import usercustomize
503 except ImportError:
504 pass
505
506
Brett Cannon0096e262004-06-05 01:12:51 +0000507def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000508 global ENABLE_USER_SITE
509
Brett Cannon0096e262004-06-05 01:12:51 +0000510 abs__file__()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000511 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000512 if (os.name == "posix" and sys.path and
513 os.path.basename(sys.path[-1]) == "Modules"):
514 addbuilddir()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000515 if ENABLE_USER_SITE is None:
516 ENABLE_USER_SITE = check_enableusersite()
517 known_paths = addusersitepackages(known_paths)
518 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000519 if sys.platform == 'os2emx':
520 setBEGINLIBPATH()
521 setquit()
522 setcopyright()
523 sethelper()
524 aliasmbcs()
525 setencoding()
526 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000527 if ENABLE_USER_SITE:
528 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000529 # Remove sys.setdefaultencoding() so that users cannot change the
530 # encoding after initialization. The test for presence is needed when
531 # this module is run as a script, because this code is executed twice.
532 if hasattr(sys, "setdefaultencoding"):
533 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000534
Brett Cannon0096e262004-06-05 01:12:51 +0000535main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000536
Christian Heimes8dc226f2008-05-06 23:45:46 +0000537def _script():
538 help = """\
539 %s [--user-base] [--user-site]
540
541 Without arguments print some useful information
542 With arguments print the value of USER_BASE and/or USER_SITE separated
543 by '%s'.
544
545 Exit codes with --user-base or --user-site:
546 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000547 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000548 2 - uses site directory is disabled by super user
549 or for security reasons
550 >2 - unknown error
551 """
552 args = sys.argv[1:]
553 if not args:
554 print("sys.path = [")
555 for dir in sys.path:
556 print(" %r," % (dir,))
557 print("]")
558 print("USER_BASE: %r (%s)" % (USER_BASE,
559 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
560 print("USER_SITE: %r (%s)" % (USER_SITE,
561 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
562 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
563 sys.exit(0)
564
565 buffer = []
566 if '--user-base' in args:
567 buffer.append(USER_BASE)
568 if '--user-site' in args:
569 buffer.append(USER_SITE)
570
571 if buffer:
572 print(os.pathsep.join(buffer))
573 if ENABLE_USER_SITE:
574 sys.exit(0)
575 elif ENABLE_USER_SITE is False:
576 sys.exit(1)
577 elif ENABLE_USER_SITE is None:
578 sys.exit(2)
579 else:
580 sys.exit(3)
581 else:
582 import textwrap
583 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
584 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000585
586if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000587 _script()