Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sysconfig.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. """Provide access to Python's configuration information. The specific
  2. configuration variables available depend heavily on the platform and
  3. configuration. The values may be retrieved using
  4. get_config_var(name), and the list of variables is available via
  5. get_config_vars().keys(). Additional convenience functions are also
  6. available.
  7. Written by: Fred L. Drake, Jr.
  8. Email: <fdrake@acm.org>
  9. """
  10. import _imp
  11. import os
  12. import re
  13. import sys
  14. from .errors import DistutilsPlatformError
  15. IS_PYPY = '__pypy__' in sys.builtin_module_names
  16. # These are needed in a couple of spots, so just compute them once.
  17. PREFIX = os.path.normpath(sys.prefix)
  18. EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
  19. BASE_PREFIX = os.path.normpath(sys.base_prefix)
  20. BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
  21. # Path to the base directory of the project. On Windows the binary may
  22. # live in project/PCbuild/win32 or project/PCbuild/amd64.
  23. # set for cross builds
  24. if "_PYTHON_PROJECT_BASE" in os.environ:
  25. project_base = os.path.abspath(os.environ["_PYTHON_PROJECT_BASE"])
  26. else:
  27. if sys.executable:
  28. project_base = os.path.dirname(os.path.abspath(sys.executable))
  29. else:
  30. # sys.executable can be empty if argv[0] has been changed and Python is
  31. # unable to retrieve the real program name
  32. project_base = os.getcwd()
  33. # python_build: (Boolean) if true, we're either building Python or
  34. # building an extension with an un-installed Python, so we use
  35. # different (hard-wired) directories.
  36. def _is_python_source_dir(d):
  37. for fn in ("Setup", "Setup.local"):
  38. if os.path.isfile(os.path.join(d, "Modules", fn)):
  39. return True
  40. return False
  41. _sys_home = getattr(sys, '_home', None)
  42. if os.name == 'nt':
  43. def _fix_pcbuild(d):
  44. if d and os.path.normcase(d).startswith(
  45. os.path.normcase(os.path.join(PREFIX, "PCbuild"))):
  46. return PREFIX
  47. return d
  48. project_base = _fix_pcbuild(project_base)
  49. _sys_home = _fix_pcbuild(_sys_home)
  50. def _python_build():
  51. if _sys_home:
  52. return _is_python_source_dir(_sys_home)
  53. return _is_python_source_dir(project_base)
  54. python_build = _python_build()
  55. # Calculate the build qualifier flags if they are defined. Adding the flags
  56. # to the include and lib directories only makes sense for an installation, not
  57. # an in-source build.
  58. build_flags = ''
  59. try:
  60. if not python_build:
  61. build_flags = sys.abiflags
  62. except AttributeError:
  63. # It's not a configure-based build, so the sys module doesn't have
  64. # this attribute, which is fine.
  65. pass
  66. def get_python_version():
  67. """Return a string containing the major and minor Python version,
  68. leaving off the patchlevel. Sample return values could be '1.5'
  69. or '2.2'.
  70. """
  71. return '%d.%d' % sys.version_info[:2]
  72. def get_python_inc(plat_specific=0, prefix=None):
  73. """Return the directory containing installed Python header files.
  74. If 'plat_specific' is false (the default), this is the path to the
  75. non-platform-specific header files, i.e. Python.h and so on;
  76. otherwise, this is the path to platform-specific header files
  77. (namely pyconfig.h).
  78. If 'prefix' is supplied, use it instead of sys.base_prefix or
  79. sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
  80. """
  81. if prefix is None:
  82. prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
  83. if os.name == "posix":
  84. if IS_PYPY and sys.version_info < (3, 8):
  85. return os.path.join(prefix, 'include')
  86. if python_build:
  87. # Assume the executable is in the build directory. The
  88. # pyconfig.h file should be in the same directory. Since
  89. # the build directory may not be the source directory, we
  90. # must use "srcdir" from the makefile to find the "Include"
  91. # directory.
  92. if plat_specific:
  93. return _sys_home or project_base
  94. else:
  95. incdir = os.path.join(get_config_var('srcdir'), 'Include')
  96. return os.path.normpath(incdir)
  97. implementation = 'pypy' if IS_PYPY else 'python'
  98. python_dir = implementation + get_python_version() + build_flags
  99. return os.path.join(prefix, "include", python_dir)
  100. elif os.name == "nt":
  101. if python_build:
  102. # Include both the include and PC dir to ensure we can find
  103. # pyconfig.h
  104. return (os.path.join(prefix, "include") + os.path.pathsep +
  105. os.path.join(prefix, "PC"))
  106. return os.path.join(prefix, "include")
  107. else:
  108. raise DistutilsPlatformError(
  109. "I don't know where Python installs its C header files "
  110. "on platform '%s'" % os.name)
  111. def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
  112. """Return the directory containing the Python library (standard or
  113. site additions).
  114. If 'plat_specific' is true, return the directory containing
  115. platform-specific modules, i.e. any module from a non-pure-Python
  116. module distribution; otherwise, return the platform-shared library
  117. directory. If 'standard_lib' is true, return the directory
  118. containing standard Python library modules; otherwise, return the
  119. directory for site-specific modules.
  120. If 'prefix' is supplied, use it instead of sys.base_prefix or
  121. sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
  122. """
  123. if IS_PYPY and sys.version_info < (3, 8):
  124. # PyPy-specific schema
  125. if prefix is None:
  126. prefix = PREFIX
  127. if standard_lib:
  128. return os.path.join(prefix, "lib-python", sys.version[0])
  129. return os.path.join(prefix, 'site-packages')
  130. if prefix is None:
  131. if standard_lib:
  132. prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
  133. else:
  134. prefix = plat_specific and EXEC_PREFIX or PREFIX
  135. if os.name == "posix":
  136. if plat_specific or standard_lib:
  137. # Platform-specific modules (any module from a non-pure-Python
  138. # module distribution) or standard Python library modules.
  139. libdir = getattr(sys, "platlibdir", "lib")
  140. else:
  141. # Pure Python
  142. libdir = "lib"
  143. implementation = 'pypy' if IS_PYPY else 'python'
  144. libpython = os.path.join(prefix, libdir,
  145. implementation + get_python_version())
  146. if standard_lib:
  147. return libpython
  148. else:
  149. return os.path.join(libpython, "site-packages")
  150. elif os.name == "nt":
  151. if standard_lib:
  152. return os.path.join(prefix, "Lib")
  153. else:
  154. return os.path.join(prefix, "Lib", "site-packages")
  155. else:
  156. raise DistutilsPlatformError(
  157. "I don't know where Python installs its library "
  158. "on platform '%s'" % os.name)
  159. def customize_compiler(compiler):
  160. """Do any platform-specific customization of a CCompiler instance.
  161. Mainly needed on Unix, so we can plug in the information that
  162. varies across Unices and is stored in Python's Makefile.
  163. """
  164. if compiler.compiler_type == "unix":
  165. if sys.platform == "darwin":
  166. # Perform first-time customization of compiler-related
  167. # config vars on OS X now that we know we need a compiler.
  168. # This is primarily to support Pythons from binary
  169. # installers. The kind and paths to build tools on
  170. # the user system may vary significantly from the system
  171. # that Python itself was built on. Also the user OS
  172. # version and build tools may not support the same set
  173. # of CPU architectures for universal builds.
  174. global _config_vars
  175. # Use get_config_var() to ensure _config_vars is initialized.
  176. if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
  177. import _osx_support
  178. _osx_support.customize_compiler(_config_vars)
  179. _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
  180. (cc, cxx, cflags, ccshared, ldshared, shlib_suffix, ar, ar_flags) = \
  181. get_config_vars('CC', 'CXX', 'CFLAGS',
  182. 'CCSHARED', 'LDSHARED', 'SHLIB_SUFFIX', 'AR', 'ARFLAGS')
  183. if 'CC' in os.environ:
  184. newcc = os.environ['CC']
  185. if('LDSHARED' not in os.environ
  186. and ldshared.startswith(cc)):
  187. # If CC is overridden, use that as the default
  188. # command for LDSHARED as well
  189. ldshared = newcc + ldshared[len(cc):]
  190. cc = newcc
  191. if 'CXX' in os.environ:
  192. cxx = os.environ['CXX']
  193. if 'LDSHARED' in os.environ:
  194. ldshared = os.environ['LDSHARED']
  195. if 'CPP' in os.environ:
  196. cpp = os.environ['CPP']
  197. else:
  198. cpp = cc + " -E" # not always
  199. if 'LDFLAGS' in os.environ:
  200. ldshared = ldshared + ' ' + os.environ['LDFLAGS']
  201. if 'CFLAGS' in os.environ:
  202. cflags = cflags + ' ' + os.environ['CFLAGS']
  203. ldshared = ldshared + ' ' + os.environ['CFLAGS']
  204. if 'CPPFLAGS' in os.environ:
  205. cpp = cpp + ' ' + os.environ['CPPFLAGS']
  206. cflags = cflags + ' ' + os.environ['CPPFLAGS']
  207. ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
  208. if 'AR' in os.environ:
  209. ar = os.environ['AR']
  210. if 'ARFLAGS' in os.environ:
  211. archiver = ar + ' ' + os.environ['ARFLAGS']
  212. else:
  213. archiver = ar + ' ' + ar_flags
  214. cc_cmd = cc + ' ' + cflags
  215. compiler.set_executables(
  216. preprocessor=cpp,
  217. compiler=cc_cmd,
  218. compiler_so=cc_cmd + ' ' + ccshared,
  219. compiler_cxx=cxx,
  220. linker_so=ldshared,
  221. linker_exe=cc,
  222. archiver=archiver)
  223. if 'RANLIB' in os.environ and compiler.executables.get('ranlib', None):
  224. compiler.set_executables(ranlib=os.environ['RANLIB'])
  225. compiler.shared_lib_extension = shlib_suffix
  226. def get_config_h_filename():
  227. """Return full pathname of installed pyconfig.h file."""
  228. if python_build:
  229. if os.name == "nt":
  230. inc_dir = os.path.join(_sys_home or project_base, "PC")
  231. else:
  232. inc_dir = _sys_home or project_base
  233. else:
  234. inc_dir = get_python_inc(plat_specific=1)
  235. return os.path.join(inc_dir, 'pyconfig.h')
  236. def get_makefile_filename():
  237. """Return full pathname of installed Makefile from the Python build."""
  238. if python_build:
  239. return os.path.join(_sys_home or project_base, "Makefile")
  240. lib_dir = get_python_lib(plat_specific=0, standard_lib=1)
  241. config_file = 'config-{}{}'.format(get_python_version(), build_flags)
  242. if hasattr(sys.implementation, '_multiarch'):
  243. config_file += '-%s' % sys.implementation._multiarch
  244. return os.path.join(lib_dir, config_file, 'Makefile')
  245. def parse_config_h(fp, g=None):
  246. """Parse a config.h-style file.
  247. A dictionary containing name/value pairs is returned. If an
  248. optional dictionary is passed in as the second argument, it is
  249. used instead of a new dictionary.
  250. """
  251. if g is None:
  252. g = {}
  253. define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
  254. undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
  255. #
  256. while True:
  257. line = fp.readline()
  258. if not line:
  259. break
  260. m = define_rx.match(line)
  261. if m:
  262. n, v = m.group(1, 2)
  263. try: v = int(v)
  264. except ValueError: pass
  265. g[n] = v
  266. else:
  267. m = undef_rx.match(line)
  268. if m:
  269. g[m.group(1)] = 0
  270. return g
  271. # Regexes needed for parsing Makefile (and similar syntaxes,
  272. # like old-style Setup files).
  273. _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
  274. _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
  275. _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
  276. def parse_makefile(fn, g=None):
  277. """Parse a Makefile-style file.
  278. A dictionary containing name/value pairs is returned. If an
  279. optional dictionary is passed in as the second argument, it is
  280. used instead of a new dictionary.
  281. """
  282. from distutils.text_file import TextFile
  283. fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape")
  284. if g is None:
  285. g = {}
  286. done = {}
  287. notdone = {}
  288. while True:
  289. line = fp.readline()
  290. if line is None: # eof
  291. break
  292. m = _variable_rx.match(line)
  293. if m:
  294. n, v = m.group(1, 2)
  295. v = v.strip()
  296. # `$$' is a literal `$' in make
  297. tmpv = v.replace('$$', '')
  298. if "$" in tmpv:
  299. notdone[n] = v
  300. else:
  301. try:
  302. v = int(v)
  303. except ValueError:
  304. # insert literal `$'
  305. done[n] = v.replace('$$', '$')
  306. else:
  307. done[n] = v
  308. # Variables with a 'PY_' prefix in the makefile. These need to
  309. # be made available without that prefix through sysconfig.
  310. # Special care is needed to ensure that variable expansion works, even
  311. # if the expansion uses the name without a prefix.
  312. renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
  313. # do variable interpolation here
  314. while notdone:
  315. for name in list(notdone):
  316. value = notdone[name]
  317. m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
  318. if m:
  319. n = m.group(1)
  320. found = True
  321. if n in done:
  322. item = str(done[n])
  323. elif n in notdone:
  324. # get it on a subsequent round
  325. found = False
  326. elif n in os.environ:
  327. # do it like make: fall back to environment
  328. item = os.environ[n]
  329. elif n in renamed_variables:
  330. if name.startswith('PY_') and name[3:] in renamed_variables:
  331. item = ""
  332. elif 'PY_' + n in notdone:
  333. found = False
  334. else:
  335. item = str(done['PY_' + n])
  336. else:
  337. done[n] = item = ""
  338. if found:
  339. after = value[m.end():]
  340. value = value[:m.start()] + item + after
  341. if "$" in after:
  342. notdone[name] = value
  343. else:
  344. try: value = int(value)
  345. except ValueError:
  346. done[name] = value.strip()
  347. else:
  348. done[name] = value
  349. del notdone[name]
  350. if name.startswith('PY_') \
  351. and name[3:] in renamed_variables:
  352. name = name[3:]
  353. if name not in done:
  354. done[name] = value
  355. else:
  356. # bogus variable reference; just drop it since we can't deal
  357. del notdone[name]
  358. fp.close()
  359. # strip spurious spaces
  360. for k, v in done.items():
  361. if isinstance(v, str):
  362. done[k] = v.strip()
  363. # save the results in the global dictionary
  364. g.update(done)
  365. return g
  366. def expand_makefile_vars(s, vars):
  367. """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
  368. 'string' according to 'vars' (a dictionary mapping variable names to
  369. values). Variables not present in 'vars' are silently expanded to the
  370. empty string. The variable values in 'vars' should not contain further
  371. variable expansions; if 'vars' is the output of 'parse_makefile()',
  372. you're fine. Returns a variable-expanded version of 's'.
  373. """
  374. # This algorithm does multiple expansion, so if vars['foo'] contains
  375. # "${bar}", it will expand ${foo} to ${bar}, and then expand
  376. # ${bar}... and so forth. This is fine as long as 'vars' comes from
  377. # 'parse_makefile()', which takes care of such expansions eagerly,
  378. # according to make's variable expansion semantics.
  379. while True:
  380. m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
  381. if m:
  382. (beg, end) = m.span()
  383. s = s[0:beg] + vars.get(m.group(1)) + s[end:]
  384. else:
  385. break
  386. return s
  387. _config_vars = None
  388. def _init_posix():
  389. """Initialize the module as appropriate for POSIX systems."""
  390. # _sysconfigdata is generated at build time, see the sysconfig module
  391. name = os.environ.get('_PYTHON_SYSCONFIGDATA_NAME',
  392. '_sysconfigdata_{abi}_{platform}_{multiarch}'.format(
  393. abi=sys.abiflags,
  394. platform=sys.platform,
  395. multiarch=getattr(sys.implementation, '_multiarch', ''),
  396. ))
  397. try:
  398. _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
  399. except ImportError:
  400. # Python 3.5 and pypy 7.3.1
  401. _temp = __import__(
  402. '_sysconfigdata', globals(), locals(), ['build_time_vars'], 0)
  403. build_time_vars = _temp.build_time_vars
  404. global _config_vars
  405. _config_vars = {}
  406. _config_vars.update(build_time_vars)
  407. def _init_nt():
  408. """Initialize the module as appropriate for NT"""
  409. g = {}
  410. # set basic install directories
  411. g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  412. g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  413. # XXX hmmm.. a normal install puts include files here
  414. g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  415. g['EXT_SUFFIX'] = _imp.extension_suffixes()[0]
  416. g['EXE'] = ".exe"
  417. g['VERSION'] = get_python_version().replace(".", "")
  418. g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
  419. global _config_vars
  420. _config_vars = g
  421. def get_config_vars(*args):
  422. """With no arguments, return a dictionary of all configuration
  423. variables relevant for the current platform. Generally this includes
  424. everything needed to build extensions and install both pure modules and
  425. extensions. On Unix, this means every variable defined in Python's
  426. installed Makefile; on Windows it's a much smaller set.
  427. With arguments, return a list of values that result from looking up
  428. each argument in the configuration variable dictionary.
  429. """
  430. global _config_vars
  431. if _config_vars is None:
  432. func = globals().get("_init_" + os.name)
  433. if func:
  434. func()
  435. else:
  436. _config_vars = {}
  437. # Normalized versions of prefix and exec_prefix are handy to have;
  438. # in fact, these are the standard versions used most places in the
  439. # Distutils.
  440. _config_vars['prefix'] = PREFIX
  441. _config_vars['exec_prefix'] = EXEC_PREFIX
  442. if not IS_PYPY:
  443. # For backward compatibility, see issue19555
  444. SO = _config_vars.get('EXT_SUFFIX')
  445. if SO is not None:
  446. _config_vars['SO'] = SO
  447. # Always convert srcdir to an absolute path
  448. srcdir = _config_vars.get('srcdir', project_base)
  449. if os.name == 'posix':
  450. if python_build:
  451. # If srcdir is a relative path (typically '.' or '..')
  452. # then it should be interpreted relative to the directory
  453. # containing Makefile.
  454. base = os.path.dirname(get_makefile_filename())
  455. srcdir = os.path.join(base, srcdir)
  456. else:
  457. # srcdir is not meaningful since the installation is
  458. # spread about the filesystem. We choose the
  459. # directory containing the Makefile since we know it
  460. # exists.
  461. srcdir = os.path.dirname(get_makefile_filename())
  462. _config_vars['srcdir'] = os.path.abspath(os.path.normpath(srcdir))
  463. # Convert srcdir into an absolute path if it appears necessary.
  464. # Normally it is relative to the build directory. However, during
  465. # testing, for example, we might be running a non-installed python
  466. # from a different directory.
  467. if python_build and os.name == "posix":
  468. base = project_base
  469. if (not os.path.isabs(_config_vars['srcdir']) and
  470. base != os.getcwd()):
  471. # srcdir is relative and we are not in the same directory
  472. # as the executable. Assume executable is in the build
  473. # directory and make srcdir absolute.
  474. srcdir = os.path.join(base, _config_vars['srcdir'])
  475. _config_vars['srcdir'] = os.path.normpath(srcdir)
  476. # OS X platforms require special customization to handle
  477. # multi-architecture, multi-os-version installers
  478. if sys.platform == 'darwin':
  479. import _osx_support
  480. _osx_support.customize_config_vars(_config_vars)
  481. if args:
  482. vals = []
  483. for name in args:
  484. vals.append(_config_vars.get(name))
  485. return vals
  486. else:
  487. return _config_vars
  488. def get_config_var(name):
  489. """Return the value of a single variable using the dictionary
  490. returned by 'get_config_vars()'. Equivalent to
  491. get_config_vars().get(name)
  492. """
  493. if name == 'SO':
  494. import warnings
  495. warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
  496. return get_config_vars().get(name)