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