]> git.proxmox.com Git - mirror_edk2.git/blame - AppPkg/Applications/Python/Python-2.7.10/PyMod-2.7.10/Lib/site.py
AppPkg/.../Python-2.7.10: Update file for Python-2.7.10 inclusion.
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / PyMod-2.7.10 / Lib / site.py
CommitLineData
3ec97ca4
DM
1"""Append module search paths for third-party packages to sys.path.\r
2\r
3****************************************************************\r
4* This module is automatically imported during initialization. *\r
5****************************************************************\r
6\r
7In earlier versions of Python (up to 1.5a3), scripts or modules that\r
8needed to use site-specific modules would place ``import site''\r
9somewhere near the top of their code. Because of the automatic\r
10import, this is no longer necessary (but code that does it still\r
11works).\r
12\r
13This will append site-specific paths to the module search path. On\r
14Unix (including Mac OSX), it starts with sys.prefix and\r
15sys.exec_prefix (if different) and appends\r
16lib/python<version>/site-packages as well as lib/site-python.\r
17On other platforms (such as Windows), it tries each of the\r
18prefixes directly, as well as with lib/site-packages appended. The\r
19resulting directories, if they exist, are appended to sys.path, and\r
20also inspected for path configuration files.\r
21\r
22A path configuration file is a file whose name has the form\r
23<package>.pth; its contents are additional directories (one per line)\r
24to be added to sys.path. Non-existing directories (or\r
25non-directories) are never added to sys.path; no directory is added to\r
26sys.path more than once. Blank lines and lines beginning with\r
27'#' are skipped. Lines starting with 'import' are executed.\r
28\r
29For example, suppose sys.prefix and sys.exec_prefix are set to\r
30/usr/local and there is a directory /usr/local/lib/python2.5/site-packages\r
31with three subdirectories, foo, bar and spam, and two path\r
32configuration files, foo.pth and bar.pth. Assume foo.pth contains the\r
33following:\r
34\r
35 # foo package configuration\r
36 foo\r
37 bar\r
38 bletch\r
39\r
40and bar.pth contains:\r
41\r
42 # bar package configuration\r
43 bar\r
44\r
45Then the following directories are added to sys.path, in this order:\r
46\r
47 /usr/local/lib/python2.5/site-packages/bar\r
48 /usr/local/lib/python2.5/site-packages/foo\r
49\r
50Note that bletch is omitted because it doesn't exist; bar precedes foo\r
51because bar.pth comes alphabetically before foo.pth; and spam is\r
52omitted because it is not mentioned in either path configuration file.\r
53\r
54After these path manipulations, an attempt is made to import a module\r
55named sitecustomize, which can perform arbitrary additional\r
56site-specific customizations. If this import fails with an\r
57ImportError exception, it is silently ignored.\r
58\r
59"""\r
60\r
61import sys\r
62import os\r
63import __builtin__\r
64import traceback\r
65\r
66# Prefixes for site-packages; add additional prefixes like /usr/local here\r
67PREFIXES = [sys.prefix, sys.exec_prefix]\r
68# Enable per user site-packages directory\r
69# set it to False to disable the feature or True to force the feature\r
70ENABLE_USER_SITE = None\r
71\r
72# for distutils.commands.install\r
73# These values are initialized by the getuserbase() and getusersitepackages()\r
74# functions, through the main() function when Python starts.\r
75USER_SITE = None\r
76USER_BASE = None\r
77\r
78\r
79def makepath(*paths):\r
80 dir = os.path.join(*paths)\r
81 try:\r
82 dir = os.path.abspath(dir)\r
83 except OSError:\r
84 pass\r
85 return dir, os.path.normcase(dir)\r
86\r
87\r
88def abs__file__():\r
89 """Set all module' __file__ attribute to an absolute path"""\r
90 for m in sys.modules.values():\r
91 if hasattr(m, '__loader__'):\r
92 continue # don't mess with a PEP 302-supplied __file__\r
93 try:\r
94 m.__file__ = os.path.abspath(m.__file__)\r
95 except (AttributeError, OSError):\r
96 pass\r
97\r
98\r
99def removeduppaths():\r
100 """ Remove duplicate entries from sys.path along with making them\r
101 absolute"""\r
102 # This ensures that the initial path provided by the interpreter contains\r
103 # only absolute pathnames, even if we're running from the build directory.\r
104 L = []\r
105 known_paths = set()\r
106 for dir in sys.path:\r
107 # Filter out duplicate paths (on case-insensitive file systems also\r
108 # if they only differ in case); turn relative paths into absolute\r
109 # paths.\r
110 dir, dircase = makepath(dir)\r
111 if not dircase in known_paths:\r
112 L.append(dir)\r
113 known_paths.add(dircase)\r
114 sys.path[:] = L\r
115 return known_paths\r
116\r
117\r
118def _init_pathinfo():\r
119 """Return a set containing all existing directory entries from sys.path"""\r
120 d = set()\r
121 for dir in sys.path:\r
122 try:\r
123 if os.path.isdir(dir):\r
124 dir, dircase = makepath(dir)\r
125 d.add(dircase)\r
126 except TypeError:\r
127 continue\r
128 return d\r
129\r
130\r
131def addpackage(sitedir, name, known_paths):\r
132 """Process a .pth file within the site-packages directory:\r
133 For each line in the file, either combine it with sitedir to a path\r
134 and add that to known_paths, or execute it if it starts with 'import '.\r
135 """\r
136 if known_paths is None:\r
137 _init_pathinfo()\r
138 reset = 1\r
139 else:\r
140 reset = 0\r
141 fullname = os.path.join(sitedir, name)\r
142 try:\r
143 f = open(fullname, "rU")\r
144 except IOError:\r
145 return\r
146 with f:\r
147 for n, line in enumerate(f):\r
148 if line.startswith("#"):\r
149 continue\r
150 try:\r
151 if line.startswith(("import ", "import\t")):\r
152 exec line\r
153 continue\r
154 line = line.rstrip()\r
155 dir, dircase = makepath(sitedir, line)\r
156 if not dircase in known_paths and os.path.exists(dir):\r
157 sys.path.append(dir)\r
158 known_paths.add(dircase)\r
159 except Exception as err:\r
160 print >>sys.stderr, "Error processing line {:d} of {}:\n".format(\r
161 n+1, fullname)\r
162 for record in traceback.format_exception(*sys.exc_info()):\r
163 for line in record.splitlines():\r
164 print >>sys.stderr, ' '+line\r
165 print >>sys.stderr, "\nRemainder of file ignored"\r
166 break\r
167 if reset:\r
168 known_paths = None\r
169 return known_paths\r
170\r
171\r
172def addsitedir(sitedir, known_paths=None):\r
173 """Add 'sitedir' argument to sys.path if missing and handle .pth files in\r
174 'sitedir'"""\r
175 if known_paths is None:\r
176 known_paths = _init_pathinfo()\r
177 reset = 1\r
178 else:\r
179 reset = 0\r
180 sitedir, sitedircase = makepath(sitedir)\r
181 if not sitedircase in known_paths:\r
182 sys.path.append(sitedir) # Add path component\r
183 try:\r
184 names = os.listdir(sitedir)\r
185 except os.error:\r
186 return\r
187 dotpth = os.extsep + "pth"\r
188 names = [name for name in names if name.endswith(dotpth)]\r
189 for name in sorted(names):\r
190 addpackage(sitedir, name, known_paths)\r
191 if reset:\r
192 known_paths = None\r
193 return known_paths\r
194\r
195\r
196def check_enableusersite():\r
197 """Check if user site directory is safe for inclusion\r
198\r
199 The function tests for the command line flag (including environment var),\r
200 process uid/gid equal to effective uid/gid.\r
201\r
202 None: Disabled for security reasons\r
203 False: Disabled by user (command line option)\r
204 True: Safe and enabled\r
205 """\r
206 if sys.flags.no_user_site:\r
207 return False\r
208\r
209 if hasattr(os, "getuid") and hasattr(os, "geteuid"):\r
210 # check process uid == effective uid\r
211 if os.geteuid() != os.getuid():\r
212 return None\r
213 if hasattr(os, "getgid") and hasattr(os, "getegid"):\r
214 # check process gid == effective gid\r
215 if os.getegid() != os.getgid():\r
216 return None\r
217\r
218 return True\r
219\r
220def getuserbase():\r
221 """Returns the `user base` directory path.\r
222\r
223 The `user base` directory can be used to store data. If the global\r
224 variable ``USER_BASE`` is not initialized yet, this function will also set\r
225 it.\r
226 """\r
227 global USER_BASE\r
228 if USER_BASE is not None:\r
229 return USER_BASE\r
230 from sysconfig import get_config_var\r
231 USER_BASE = get_config_var('userbase')\r
232 return USER_BASE\r
233\r
234def getusersitepackages():\r
235 """Returns the user-specific site-packages directory path.\r
236\r
237 If the global variable ``USER_SITE`` is not initialized yet, this\r
238 function will also set it.\r
239 """\r
240 global USER_SITE\r
241 user_base = getuserbase() # this will also set USER_BASE\r
242\r
243 if USER_SITE is not None:\r
244 return USER_SITE\r
245\r
246 from sysconfig import get_path\r
247 import os\r
248\r
249 if sys.platform == 'darwin':\r
250 from sysconfig import get_config_var\r
251 if get_config_var('PYTHONFRAMEWORK'):\r
252 USER_SITE = get_path('purelib', 'osx_framework_user')\r
253 return USER_SITE\r
254\r
255 USER_SITE = get_path('purelib', '%s_user' % os.name)\r
256 return USER_SITE\r
257\r
258def addusersitepackages(known_paths):\r
259 """Add a per user site-package to sys.path\r
260\r
261 Each user has its own python directory with site-packages in the\r
262 home directory.\r
263 """\r
264 # get the per user site-package path\r
265 # this call will also make sure USER_BASE and USER_SITE are set\r
266 user_site = getusersitepackages()\r
267\r
268 if ENABLE_USER_SITE and os.path.isdir(user_site):\r
269 addsitedir(user_site, known_paths)\r
270 return known_paths\r
271\r
272def getsitepackages():\r
273 """Returns a list containing all global site-packages directories\r
274 (and possibly site-python).\r
275\r
276 For each directory present in the global ``PREFIXES``, this function\r
277 will find its `site-packages` subdirectory depending on the system\r
278 environment, and will return a list of full paths.\r
279 """\r
280 sitepackages = []\r
281 seen = set()\r
282\r
283 for prefix in PREFIXES:\r
284 if not prefix or prefix in seen:\r
285 continue\r
286 seen.add(prefix)\r
287\r
288 if sys.platform in ('os2emx', 'riscos'):\r
289 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))\r
290 elif os.sep == '/':\r
291 sitepackages.append(os.path.join(prefix, "lib",\r
292 "python" + sys.version[:3],\r
293 "site-packages"))\r
294 sitepackages.append(os.path.join(prefix, "lib", "site-python"))\r
295 else:\r
296 sitepackages.append(prefix)\r
297 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))\r
298 if sys.platform == "darwin":\r
299 # for framework builds *only* we add the standard Apple\r
300 # locations.\r
301 from sysconfig import get_config_var\r
302 framework = get_config_var("PYTHONFRAMEWORK")\r
303 if framework:\r
304 sitepackages.append(\r
305 os.path.join("/Library", framework,\r
306 sys.version[:3], "site-packages"))\r
307 return sitepackages\r
308\r
309def addsitepackages(known_paths):\r
310 """Add site-packages (and possibly site-python) to sys.path"""\r
311 for sitedir in getsitepackages():\r
312 if os.path.isdir(sitedir):\r
313 addsitedir(sitedir, known_paths)\r
314\r
315 return known_paths\r
316\r
317def setBEGINLIBPATH():\r
318 """The OS/2 EMX port has optional extension modules that do double duty\r
319 as DLLs (and must use the .DLL file extension) for other extensions.\r
320 The library search path needs to be amended so these will be found\r
321 during module import. Use BEGINLIBPATH so that these are at the start\r
322 of the library search path.\r
323\r
324 """\r
325 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")\r
326 libpath = os.environ['BEGINLIBPATH'].split(';')\r
327 if libpath[-1]:\r
328 libpath.append(dllpath)\r
329 else:\r
330 libpath[-1] = dllpath\r
331 os.environ['BEGINLIBPATH'] = ';'.join(libpath)\r
332\r
333\r
334def setquit():\r
335 """Define new builtins 'quit' and 'exit'.\r
336\r
337 These are objects which make the interpreter exit when called.\r
338 The repr of each object contains a hint at how it works.\r
339\r
340 """\r
341 if os.sep == ':':\r
342 eof = 'Cmd-Q'\r
343 elif os.sep == '\\':\r
344 eof = 'Ctrl-Z plus Return'\r
345 else:\r
346 eof = 'Ctrl-D (i.e. EOF)'\r
347\r
348 class Quitter(object):\r
349 def __init__(self, name):\r
350 self.name = name\r
351 def __repr__(self):\r
352 return 'Use %s() or %s to exit' % (self.name, eof)\r
353 def __call__(self, code=None):\r
354 # Shells like IDLE catch the SystemExit, but listen when their\r
355 # stdin wrapper is closed.\r
356 try:\r
357 sys.stdin.close()\r
358 except:\r
359 pass\r
360 raise SystemExit(code)\r
361 __builtin__.quit = Quitter('quit')\r
362 __builtin__.exit = Quitter('exit')\r
363\r
364\r
365class _Printer(object):\r
366 """interactive prompt objects for printing the license text, a list of\r
367 contributors and the copyright notice."""\r
368\r
369 MAXLINES = 23\r
370\r
371 def __init__(self, name, data, files=(), dirs=()):\r
372 self.__name = name\r
373 self.__data = data\r
374 self.__files = files\r
375 self.__dirs = dirs\r
376 self.__lines = None\r
377\r
378 def __setup(self):\r
379 if self.__lines:\r
380 return\r
381 data = None\r
382 for dir in self.__dirs:\r
383 for filename in self.__files:\r
384 filename = os.path.join(dir, filename)\r
385 try:\r
386 fp = file(filename, "rU")\r
387 data = fp.read()\r
388 fp.close()\r
389 break\r
390 except IOError:\r
391 pass\r
392 if data:\r
393 break\r
394 if not data:\r
395 data = self.__data\r
396 self.__lines = data.split('\n')\r
397 self.__linecnt = len(self.__lines)\r
398\r
399 def __repr__(self):\r
400 self.__setup()\r
401 if len(self.__lines) <= self.MAXLINES:\r
402 return "\n".join(self.__lines)\r
403 else:\r
404 return "Type %s() to see the full %s text" % ((self.__name,)*2)\r
405\r
406 def __call__(self):\r
407 self.__setup()\r
408 prompt = 'Hit Return for more, or q (and Return) to quit: '\r
409 lineno = 0\r
410 while 1:\r
411 try:\r
412 for i in range(lineno, lineno + self.MAXLINES):\r
413 print self.__lines[i]\r
414 except IndexError:\r
415 break\r
416 else:\r
417 lineno += self.MAXLINES\r
418 key = None\r
419 while key is None:\r
420 key = raw_input(prompt)\r
421 if key not in ('', 'q'):\r
422 key = None\r
423 if key == 'q':\r
424 break\r
425\r
426def setcopyright():\r
427 """Set 'copyright' and 'credits' in __builtin__"""\r
428 __builtin__.copyright = _Printer("copyright", sys.copyright)\r
429 if sys.platform[:4] == 'java':\r
430 __builtin__.credits = _Printer(\r
431 "credits",\r
432 "Jython is maintained by the Jython developers (www.jython.org).")\r
433 else:\r
434 __builtin__.credits = _Printer("credits", """\\r
435 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\r
436 for supporting Python development. See www.python.org for more information.""")\r
437 here = os.path.dirname(os.__file__)\r
438 __builtin__.license = _Printer(\r
439 "license", "See https://www.python.org/psf/license/",\r
440 ["LICENSE.txt", "LICENSE"],\r
441 [os.path.join(here, os.pardir), here, os.curdir])\r
442\r
443\r
444class _Helper(object):\r
445 """Define the builtin 'help'.\r
446 This is a wrapper around pydoc.help (with a twist).\r
447\r
448 """\r
449\r
450 def __repr__(self):\r
451 return "Type help() for interactive help, " \\r
452 "or help(object) for help about object."\r
453 def __call__(self, *args, **kwds):\r
454 import pydoc\r
455 return pydoc.help(*args, **kwds)\r
456\r
457def sethelper():\r
458 __builtin__.help = _Helper()\r
459\r
460def aliasmbcs():\r
461 """On Windows, some default encodings are not provided by Python,\r
462 while they are always available as "mbcs" in each locale. Make\r
463 them usable by aliasing to "mbcs" in such a case."""\r
464 if sys.platform == 'win32':\r
465 import locale, codecs\r
466 enc = locale.getdefaultlocale()[1]\r
467 if enc.startswith('cp'): # "cp***" ?\r
468 try:\r
469 codecs.lookup(enc)\r
470 except LookupError:\r
471 import encodings\r
472 encodings._cache[enc] = encodings._unknown\r
473 encodings.aliases.aliases[enc] = 'mbcs'\r
474\r
475def setencoding():\r
476 """Set the string encoding used by the Unicode implementation. The\r
477 default is 'ascii', but if you're willing to experiment, you can\r
478 change this."""\r
479 encoding = "ascii" # Default value set by _PyUnicode_Init()\r
480 if 0:\r
481 # Enable to support locale aware default string encodings.\r
482 import locale\r
483 loc = locale.getdefaultlocale()\r
484 if loc[1]:\r
485 encoding = loc[1]\r
486 if 0:\r
487 # Enable to switch off string to Unicode coercion and implicit\r
488 # Unicode to string conversion.\r
489 encoding = "undefined"\r
490 if encoding != "ascii":\r
491 # On Non-Unicode builds this will raise an AttributeError...\r
492 sys.setdefaultencoding(encoding) # Needs Python Unicode build !\r
493\r
494\r
495def execsitecustomize():\r
496 """Run custom site specific code, if available."""\r
497 try:\r
498 import sitecustomize\r
499 except ImportError:\r
500 pass\r
501 except Exception:\r
502 if sys.flags.verbose:\r
503 sys.excepthook(*sys.exc_info())\r
504 else:\r
505 print >>sys.stderr, \\r
506 "'import sitecustomize' failed; use -v for traceback"\r
507\r
508\r
509def execusercustomize():\r
510 """Run custom user specific code, if available."""\r
511 try:\r
512 import usercustomize\r
513 except ImportError:\r
514 pass\r
515 except Exception:\r
516 if sys.flags.verbose:\r
517 sys.excepthook(*sys.exc_info())\r
518 else:\r
519 print>>sys.stderr, \\r
520 "'import usercustomize' failed; use -v for traceback"\r
521\r
522\r
523def main():\r
524 global ENABLE_USER_SITE\r
525\r
526 abs__file__()\r
527 known_paths = removeduppaths()\r
528 if ENABLE_USER_SITE is None:\r
529 ENABLE_USER_SITE = check_enableusersite()\r
530 known_paths = addusersitepackages(known_paths)\r
531 known_paths = addsitepackages(known_paths)\r
532 if sys.platform == 'os2emx':\r
533 setBEGINLIBPATH()\r
534 setquit()\r
535 setcopyright()\r
536 sethelper()\r
537 aliasmbcs()\r
538 setencoding()\r
539 execsitecustomize()\r
540 if ENABLE_USER_SITE:\r
541 execusercustomize()\r
542 # Remove sys.setdefaultencoding() so that users cannot change the\r
543 # encoding after initialization. The test for presence is needed when\r
544 # this module is run as a script, because this code is executed twice.\r
545 if hasattr(sys, "setdefaultencoding"):\r
546 del sys.setdefaultencoding\r
547\r
548main()\r
549\r
550def _script():\r
551 help = """\\r
552 %s [--user-base] [--user-site]\r
553\r
554 Without arguments print some useful information\r
555 With arguments print the value of USER_BASE and/or USER_SITE separated\r
556 by '%s'.\r
557\r
558 Exit codes with --user-base or --user-site:\r
559 0 - user site directory is enabled\r
560 1 - user site directory is disabled by user\r
561 2 - uses site directory is disabled by super user\r
562 or for security reasons\r
563 >2 - unknown error\r
564 """\r
565 args = sys.argv[1:]\r
566 if not args:\r
567 print "sys.path = ["\r
568 for dir in sys.path:\r
569 print " %r," % (dir,)\r
570 print "]"\r
571 print "USER_BASE: %r (%s)" % (USER_BASE,\r
572 "exists" if os.path.isdir(USER_BASE) else "doesn't exist")\r
573 print "USER_SITE: %r (%s)" % (USER_SITE,\r
574 "exists" if os.path.isdir(USER_SITE) else "doesn't exist")\r
575 print "ENABLE_USER_SITE: %r" % ENABLE_USER_SITE\r
576 sys.exit(0)\r
577\r
578 buffer = []\r
579 if '--user-base' in args:\r
580 buffer.append(USER_BASE)\r
581 if '--user-site' in args:\r
582 buffer.append(USER_SITE)\r
583\r
584 if buffer:\r
585 print os.pathsep.join(buffer)\r
586 if ENABLE_USER_SITE:\r
587 sys.exit(0)\r
588 elif ENABLE_USER_SITE is False:\r
589 sys.exit(1)\r
590 elif ENABLE_USER_SITE is None:\r
591 sys.exit(2)\r
592 else:\r
593 sys.exit(3)\r
594 else:\r
595 import textwrap\r
596 print textwrap.dedent(help % (sys.argv[0], os.pathsep))\r
597 sys.exit(10)\r
598\r
599if __name__ == '__main__':\r
600 _script()\r