sysconfig.py 22 KB

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