sysconfig.py 18 KB

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