]>
git.proxmox.com Git - mirror_edk2.git/blob - AppPkg/Applications/Python/Python-2.7.10/Lib/sysconfig.py
1 """Provide access to Python's configuration information.
6 from os
.path
import pardir
, realpath
10 'stdlib': '{base}/lib/python{py_version_short}',
11 'platstdlib': '{platbase}/lib/python{py_version_short}',
12 'purelib': '{base}/lib/python{py_version_short}/site-packages',
13 'platlib': '{platbase}/lib/python{py_version_short}/site-packages',
14 'include': '{base}/include/python{py_version_short}',
15 'platinclude': '{platbase}/include/python{py_version_short}',
16 'scripts': '{base}/bin',
20 'stdlib': '{base}/lib/python',
21 'platstdlib': '{base}/lib/python',
22 'purelib': '{base}/lib/python',
23 'platlib': '{base}/lib/python',
24 'include': '{base}/include/python',
25 'platinclude': '{base}/include/python',
26 'scripts': '{base}/bin',
30 'stdlib': '{base}/Lib',
31 'platstdlib': '{base}/Lib',
32 'purelib': '{base}/Lib/site-packages',
33 'platlib': '{base}/Lib/site-packages',
34 'include': '{base}/Include',
35 'platinclude': '{base}/Include',
36 'scripts': '{base}/Scripts',
40 'stdlib': '{base}/Lib',
41 'platstdlib': '{base}/Lib',
42 'purelib': '{base}/Lib/site-packages',
43 'platlib': '{base}/Lib/site-packages',
44 'include': '{base}/Include',
45 'platinclude': '{base}/Include',
46 'scripts': '{base}/Scripts',
50 'stdlib': '{userbase}/lib/python{py_version_short}',
51 'platstdlib': '{userbase}/lib/python{py_version_short}',
52 'purelib': '{userbase}/lib/python{py_version_short}/site-packages',
53 'platlib': '{userbase}/lib/python{py_version_short}/site-packages',
54 'include': '{userbase}/include/python{py_version_short}',
55 'scripts': '{userbase}/bin',
56 'data' : '{userbase}',
59 'stdlib': '{userbase}/Python{py_version_nodot}',
60 'platstdlib': '{userbase}/Python{py_version_nodot}',
61 'purelib': '{userbase}/Python{py_version_nodot}/site-packages',
62 'platlib': '{userbase}/Python{py_version_nodot}/site-packages',
63 'include': '{userbase}/Python{py_version_nodot}/Include',
64 'scripts': '{userbase}/Scripts',
65 'data' : '{userbase}',
68 'stdlib': '{userbase}/lib/python{py_version_short}',
69 'platstdlib': '{userbase}/lib/python{py_version_short}',
70 'purelib': '{userbase}/lib/python{py_version_short}/site-packages',
71 'platlib': '{userbase}/lib/python{py_version_short}/site-packages',
72 'include': '{userbase}/include/python{py_version_short}',
73 'scripts': '{userbase}/bin',
74 'data' : '{userbase}',
76 'osx_framework_user': {
77 'stdlib': '{userbase}/lib/python',
78 'platstdlib': '{userbase}/lib/python',
79 'purelib': '{userbase}/lib/python/site-packages',
80 'platlib': '{userbase}/lib/python/site-packages',
81 'include': '{userbase}/include',
82 'scripts': '{userbase}/bin',
83 'data' : '{userbase}',
87 _SCHEME_KEYS
= ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include',
89 _PY_VERSION
= sys
.version
.split()[0]
90 _PY_VERSION_SHORT
= sys
.version
[:3]
91 _PY_VERSION_SHORT_NO_DOT
= _PY_VERSION
[0] + _PY_VERSION
[2]
92 _PREFIX
= os
.path
.normpath(sys
.prefix
)
93 _EXEC_PREFIX
= os
.path
.normpath(sys
.exec_prefix
)
97 def _safe_realpath(path
):
104 _PROJECT_BASE
= os
.path
.dirname(_safe_realpath(sys
.executable
))
106 # sys.executable can be empty if argv[0] has been changed and Python is
107 # unable to retrieve the real program name
108 _PROJECT_BASE
= _safe_realpath(os
.getcwd())
110 if os
.name
== "nt" and "pcbuild" in _PROJECT_BASE
[-8:].lower():
111 _PROJECT_BASE
= _safe_realpath(os
.path
.join(_PROJECT_BASE
, pardir
))
113 if os
.name
== "nt" and "\\pc\\v" in _PROJECT_BASE
[-10:].lower():
114 _PROJECT_BASE
= _safe_realpath(os
.path
.join(_PROJECT_BASE
, pardir
, pardir
))
116 if os
.name
== "nt" and "\\pcbuild\\amd64" in _PROJECT_BASE
[-14:].lower():
117 _PROJECT_BASE
= _safe_realpath(os
.path
.join(_PROJECT_BASE
, pardir
, pardir
))
119 # set for cross builds
120 if "_PYTHON_PROJECT_BASE" in os
.environ
:
121 # the build directory for posix builds
122 _PROJECT_BASE
= os
.path
.normpath(os
.path
.abspath("."))
123 def is_python_build():
124 for fn
in ("Setup.dist", "Setup.local"):
125 if os
.path
.isfile(os
.path
.join(_PROJECT_BASE
, "Modules", fn
)):
129 _PYTHON_BUILD
= is_python_build()
132 for scheme
in ('posix_prefix', 'posix_home'):
133 _INSTALL_SCHEMES
[scheme
]['include'] = '{projectbase}/Include'
134 _INSTALL_SCHEMES
[scheme
]['platinclude'] = '{srcdir}'
136 def _subst_vars(s
, local_vars
):
138 return s
.format(**local_vars
)
141 return s
.format(**os
.environ
)
142 except KeyError, var
:
143 raise AttributeError('{%s}' % var
)
145 def _extend_dict(target_dict
, other_dict
):
146 target_keys
= target_dict
.keys()
147 for key
, value
in other_dict
.items():
148 if key
in target_keys
:
150 target_dict
[key
] = value
152 def _expand_vars(scheme
, vars):
156 _extend_dict(vars, get_config_vars())
158 for key
, value
in _INSTALL_SCHEMES
[scheme
].items():
159 if os
.name
in ('posix', 'nt'):
160 value
= os
.path
.expanduser(value
)
161 res
[key
] = os
.path
.normpath(_subst_vars(value
, vars))
164 def _get_default_scheme():
165 if os
.name
== 'posix':
166 # the default scheme for posix is posix_prefix
167 return 'posix_prefix'
171 env_base
= os
.environ
.get("PYTHONUSERBASE", None)
173 return os
.path
.expanduser(os
.path
.join(*args
))
175 # what about 'os2emx', 'riscos' ?
177 base
= os
.environ
.get("APPDATA") or "~"
178 return env_base
if env_base
else joinuser(base
, "Python")
180 if sys
.platform
== "darwin":
181 framework
= get_config_var("PYTHONFRAMEWORK")
183 return env_base
if env_base
else \
184 joinuser("~", "Library", framework
, "%d.%d"
185 % (sys
.version_info
[:2]))
187 return env_base
if env_base
else joinuser("~", ".local")
190 def _parse_makefile(filename
, vars=None):
191 """Parse a Makefile-style file.
193 A dictionary containing name/value pairs is returned. If an
194 optional dictionary is passed in as the second argument, it is
195 used instead of a new dictionary.
198 # Regexes needed for parsing Makefile (and similar syntaxes,
199 # like old-style Setup files).
200 _variable_rx
= re
.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
201 _findvar1_rx
= re
.compile(r
"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
202 _findvar2_rx
= re
.compile(r
"\${([A-Za-z][A-Za-z0-9_]*)}")
209 with
open(filename
) as f
:
210 lines
= f
.readlines()
213 if line
.startswith('#') or line
.strip() == '':
215 m
= _variable_rx
.match(line
)
219 # `$$' is a literal `$' in make
220 tmpv
= v
.replace('$$', '')
229 done
[n
] = v
.replace('$$', '$')
233 # do variable interpolation here
235 for name
in notdone
.keys():
236 value
= notdone
[name
]
237 m
= _findvar1_rx
.search(value
) or _findvar2_rx
.search(value
)
244 # get it on a subsequent round
246 elif n
in os
.environ
:
247 # do it like make: fall back to environment
252 after
= value
[m
.end():]
253 value
= value
[:m
.start()] + item
+ after
255 notdone
[name
] = value
257 try: value
= int(value
)
259 done
[name
] = value
.strip()
264 # bogus variable reference; just drop it since we can't deal
266 # strip spurious spaces
267 for k
, v
in done
.items():
268 if isinstance(v
, str):
271 # save the results in the global dictionary
276 def get_makefile_filename():
277 """Return the path of the Makefile."""
279 return os
.path
.join(_PROJECT_BASE
, "Makefile")
280 return os
.path
.join(get_path('platstdlib'), "config", "Makefile")
282 # Issue #22199: retain undocumented private name for compatibility
283 _get_makefile_filename
= get_makefile_filename
285 def _generate_posix_vars():
286 """Generate the Python module containing build-time variables."""
289 # load the installed Makefile:
290 makefile
= get_makefile_filename()
292 _parse_makefile(makefile
, vars)
294 msg
= "invalid Python installation: unable to open %s" % makefile
295 if hasattr(e
, "strerror"):
296 msg
= msg
+ " (%s)" % e
.strerror
299 # load the installed pyconfig.h:
300 config_h
= get_config_h_filename()
302 with
open(config_h
) as f
:
303 parse_config_h(f
, vars)
305 msg
= "invalid Python installation: unable to open %s" % config_h
306 if hasattr(e
, "strerror"):
307 msg
= msg
+ " (%s)" % e
.strerror
310 # On AIX, there are wrong paths to the linker scripts in the Makefile
311 # -- these paths are relative to the Python source, but when installed
312 # the scripts are in another directory.
314 vars['LDSHARED'] = vars['BLDSHARED']
316 # There's a chicken-and-egg situation on OS X with regards to the
317 # _sysconfigdata module after the changes introduced by #15298:
318 # get_config_vars() is called by get_platform() as part of the
319 # `make pybuilddir.txt` target -- which is a precursor to the
320 # _sysconfigdata.py module being constructed. Unfortunately,
321 # get_config_vars() eventually calls _init_posix(), which attempts
322 # to import _sysconfigdata, which we won't have built yet. In order
323 # for _init_posix() to work, if we're on Darwin, just mock up the
324 # _sysconfigdata module manually and populate it with the build vars.
325 # This is more than sufficient for ensuring the subsequent call to
326 # get_platform() succeeds.
327 name
= '_sysconfigdata'
328 if 'darwin' in sys
.platform
:
330 module
= imp
.new_module(name
)
331 module
.build_time_vars
= vars
332 sys
.modules
[name
] = module
334 pybuilddir
= 'build/lib.%s-%s' % (get_platform(), sys
.version
[:3])
335 if hasattr(sys
, "gettotalrefcount"):
336 pybuilddir
+= '-pydebug'
338 os
.makedirs(pybuilddir
)
341 destfile
= os
.path
.join(pybuilddir
, name
+ '.py')
343 with
open(destfile
, 'wb') as f
:
344 f
.write('# system configuration generated and used by'
345 ' the sysconfig module\n')
346 f
.write('build_time_vars = ')
347 pprint
.pprint(vars, stream
=f
)
349 # Create file used for sys.path fixup -- see Modules/getpath.c
350 with
open('pybuilddir.txt', 'w') as f
:
353 def _init_posix(vars):
354 """Initialize the module as appropriate for POSIX systems."""
355 # _sysconfigdata is generated at build time, see _generate_posix_vars()
356 from _sysconfigdata
import build_time_vars
357 vars.update(build_time_vars
)
359 def _init_non_posix(vars):
360 """Initialize the module as appropriate for NT"""
361 # set basic install directories
362 vars['LIBDEST'] = get_path('stdlib')
363 vars['BINLIBDEST'] = get_path('platstdlib')
364 vars['INCLUDEPY'] = get_path('include')
367 vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
368 vars['BINDIR'] = os
.path
.dirname(_safe_realpath(sys
.executable
))
375 def parse_config_h(fp
, vars=None):
376 """Parse a config.h-style file.
378 A dictionary containing name/value pairs is returned. If an
379 optional dictionary is passed in as the second argument, it is
380 used instead of a new dictionary.
385 define_rx
= re
.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
386 undef_rx
= re
.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
392 m
= define_rx
.match(line
)
396 except ValueError: pass
399 m
= undef_rx
.match(line
)
404 def get_config_h_filename():
405 """Returns the path of pyconfig.h."""
408 inc_dir
= os
.path
.join(_PROJECT_BASE
, "PC")
410 inc_dir
= _PROJECT_BASE
412 inc_dir
= get_path('platinclude')
413 return os
.path
.join(inc_dir
, 'pyconfig.h')
415 def get_scheme_names():
416 """Returns a tuple containing the schemes names."""
417 schemes
= _INSTALL_SCHEMES
.keys()
419 return tuple(schemes
)
421 def get_path_names():
422 """Returns a tuple containing the paths names."""
425 def get_paths(scheme
=_get_default_scheme(), vars=None, expand
=True):
426 """Returns a mapping containing an install scheme.
428 ``scheme`` is the install scheme name. If not provided, it will
429 return the default scheme for the current platform.
432 return _expand_vars(scheme
, vars)
434 return _INSTALL_SCHEMES
[scheme
]
436 def get_path(name
, scheme
=_get_default_scheme(), vars=None, expand
=True):
437 """Returns a path corresponding to the scheme.
439 ``scheme`` is the install scheme name.
441 return get_paths(scheme
, vars, expand
)[name
]
443 def get_config_vars(*args
):
444 """With no arguments, return a dictionary of all configuration
445 variables relevant for the current platform.
447 On Unix, this means every variable defined in Python's installed Makefile;
448 On Windows and Mac OS it's a much smaller set.
450 With arguments, return a list of values that result from looking up
451 each argument in the configuration variable dictionary.
455 if _CONFIG_VARS
is None:
457 # Normalized versions of prefix and exec_prefix are handy to have;
458 # in fact, these are the standard versions used most places in the
460 _CONFIG_VARS
['prefix'] = _PREFIX
461 _CONFIG_VARS
['exec_prefix'] = _EXEC_PREFIX
462 _CONFIG_VARS
['py_version'] = _PY_VERSION
463 _CONFIG_VARS
['py_version_short'] = _PY_VERSION_SHORT
464 _CONFIG_VARS
['py_version_nodot'] = _PY_VERSION
[0] + _PY_VERSION
[2]
465 _CONFIG_VARS
['base'] = _PREFIX
466 _CONFIG_VARS
['platbase'] = _EXEC_PREFIX
467 _CONFIG_VARS
['projectbase'] = _PROJECT_BASE
469 if os
.name
in ('nt', 'os2'):
470 _init_non_posix(_CONFIG_VARS
)
471 if os
.name
== 'posix':
472 _init_posix(_CONFIG_VARS
)
474 # Setting 'userbase' is done below the call to the
475 # init function to enable using 'get_config_var' in
477 _CONFIG_VARS
['userbase'] = _getuserbase()
479 if 'srcdir' not in _CONFIG_VARS
:
480 _CONFIG_VARS
['srcdir'] = _PROJECT_BASE
482 # Convert srcdir into an absolute path if it appears necessary.
483 # Normally it is relative to the build directory. However, during
484 # testing, for example, we might be running a non-installed python
485 # from a different directory.
486 if _PYTHON_BUILD
and os
.name
== "posix":
492 if (not os
.path
.isabs(_CONFIG_VARS
['srcdir']) and
494 # srcdir is relative and we are not in the same directory
495 # as the executable. Assume executable is in the build
496 # directory and make srcdir absolute.
497 srcdir
= os
.path
.join(base
, _CONFIG_VARS
['srcdir'])
498 _CONFIG_VARS
['srcdir'] = os
.path
.normpath(srcdir
)
500 # OS X platforms require special customization to handle
501 # multi-architecture, multi-os-version installers
502 if sys
.platform
== 'darwin':
504 _osx_support
.customize_config_vars(_CONFIG_VARS
)
509 vals
.append(_CONFIG_VARS
.get(name
))
514 def get_config_var(name
):
515 """Return the value of a single variable using the dictionary returned by
518 Equivalent to get_config_vars().get(name)
520 return get_config_vars().get(name
)
523 """Return a string that identifies the current platform.
525 This is used mainly to distinguish platform-specific build directories and
526 platform-specific built distributions. Typically includes the OS name
527 and version and the architecture (as supplied by 'os.uname()'),
528 although the exact information included depends on the OS; eg. for IRIX
529 the architecture isn't particularly important (IRIX only runs on SGI
530 hardware), but for Linux the kernel version isn't particularly
533 Examples of returned values:
540 Windows will return one of:
541 win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
542 win-ia64 (64bit Windows on Itanium)
543 win32 (all others - specifically, sys.platform is returned)
545 For other non-POSIX platforms, currently just returns 'sys.platform'.
549 # sniff sys.version for architecture.
551 i
= sys
.version
.find(prefix
)
554 j
= sys
.version
.find(")", i
)
555 look
= sys
.version
[i
+len(prefix
):j
].lower()
558 if look
== 'itanium':
562 # Set for cross builds explicitly
563 if "_PYTHON_HOST_PLATFORM" in os
.environ
:
564 return os
.environ
["_PYTHON_HOST_PLATFORM"]
566 if os
.name
!= "posix" or not hasattr(os
, 'uname'):
567 # XXX what about the architecture? NT is Intel or Alpha,
568 # Mac OS is M68k or PPC, etc.
571 # Try to distinguish various flavours of Unix
572 osname
, host
, release
, version
, machine
= os
.uname()
574 # Convert the OS name to lowercase, remove '/' characters
575 # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh")
576 osname
= osname
.lower().replace('/', '')
577 machine
= machine
.replace(' ', '_')
578 machine
= machine
.replace('/', '-')
580 if osname
[:5] == "linux":
581 # At least on Linux/Intel, 'machine' is the processor --
583 # XXX what about Alpha, SPARC, etc?
584 return "%s-%s" % (osname
, machine
)
585 elif osname
[:5] == "sunos":
586 if release
[0] >= "5": # SunOS 5 == Solaris 2
588 release
= "%d.%s" % (int(release
[0]) - 3, release
[2:])
589 # We can't use "platform.architecture()[0]" because a
590 # bootstrap problem. We use a dict to get an error
591 # if some suspicious happens.
592 bitness
= {2147483647:"32bit", 9223372036854775807:"64bit"}
593 machine
+= ".%s" % bitness
[sys
.maxint
]
594 # fall through to standard osname-release-machine representation
595 elif osname
[:4] == "irix": # could be "irix64"!
596 return "%s-%s" % (osname
, release
)
597 elif osname
[:3] == "aix":
598 return "%s-%s.%s" % (osname
, version
, release
)
599 elif osname
[:6] == "cygwin":
601 rel_re
= re
.compile (r
'[\d.]+')
602 m
= rel_re
.match(release
)
605 elif osname
[:6] == "darwin":
607 osname
, release
, machine
= _osx_support
.get_platform_osx(
609 osname
, release
, machine
)
611 return "%s-%s-%s" % (osname
, release
, machine
)
614 def get_python_version():
615 return _PY_VERSION_SHORT
618 def _print_dict(title
, data
):
619 for index
, (key
, value
) in enumerate(sorted(data
.items())):
621 print '%s: ' % (title
)
622 print '\t%s = "%s"' % (key
, value
)
626 """Display all information sysconfig detains."""
627 if '--generate-posix-vars' in sys
.argv
:
628 _generate_posix_vars()
630 print 'Platform: "%s"' % get_platform()
631 print 'Python version: "%s"' % get_python_version()
632 print 'Current installation scheme: "%s"' % _get_default_scheme()
634 _print_dict('Paths', get_paths())
636 _print_dict('Variables', get_config_vars())
639 if __name__
== '__main__':