sysconfig.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. def _get_python_inc_posix(prefix, spec_prefix, plat_specific):
  104. if IS_PYPY and sys.version_info < (3, 8):
  105. return os.path.join(prefix, 'include')
  106. return (
  107. _get_python_inc_posix_python(plat_specific)
  108. or _get_python_inc_from_config(plat_specific, spec_prefix)
  109. or _get_python_inc_posix_prefix(prefix)
  110. )
  111. def _get_python_inc_posix_python(plat_specific):
  112. """
  113. Assume the executable is in the build directory. The
  114. pyconfig.h file should be in the same directory. Since
  115. the build directory may not be the source directory,
  116. use "srcdir" from the makefile to find the "Include"
  117. directory.
  118. """
  119. if not python_build:
  120. return
  121. if plat_specific:
  122. return _sys_home or project_base
  123. incdir = os.path.join(get_config_var('srcdir'), 'Include')
  124. return os.path.normpath(incdir)
  125. def _get_python_inc_from_config(plat_specific, spec_prefix):
  126. """
  127. If no prefix was explicitly specified, provide the include
  128. directory from the config vars. Useful when
  129. cross-compiling, since the config vars may come from
  130. the host
  131. platform Python installation, while the current Python
  132. executable is from the build platform installation.
  133. >>> monkeypatch = getfixture('monkeypatch')
  134. >>> gpifc = _get_python_inc_from_config
  135. >>> monkeypatch.setitem(gpifc.__globals__, 'get_config_var', str.lower)
  136. >>> gpifc(False, '/usr/bin/')
  137. >>> gpifc(False, '')
  138. >>> gpifc(False, None)
  139. 'includepy'
  140. >>> gpifc(True, None)
  141. 'confincludepy'
  142. """
  143. if spec_prefix is None:
  144. return get_config_var('CONF' * plat_specific + 'INCLUDEPY')
  145. def _get_python_inc_posix_prefix(prefix):
  146. implementation = 'pypy' if IS_PYPY else 'python'
  147. python_dir = implementation + get_python_version() + build_flags
  148. return os.path.join(prefix, "include", python_dir)
  149. def _get_python_inc_nt(prefix, spec_prefix, plat_specific):
  150. if python_build:
  151. # Include both the include and PC dir to ensure we can find
  152. # pyconfig.h
  153. return (
  154. os.path.join(prefix, "include")
  155. + os.path.pathsep
  156. + os.path.join(prefix, "PC")
  157. )
  158. return os.path.join(prefix, "include")
  159. # allow this behavior to be monkey-patched. Ref pypa/distutils#2.
  160. def _posix_lib(standard_lib, libpython, early_prefix, prefix):
  161. if standard_lib:
  162. return libpython
  163. else:
  164. return os.path.join(libpython, "site-packages")
  165. def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
  166. """Return the directory containing the Python library (standard or
  167. site additions).
  168. If 'plat_specific' is true, return the directory containing
  169. platform-specific modules, i.e. any module from a non-pure-Python
  170. module distribution; otherwise, return the platform-shared library
  171. directory. If 'standard_lib' is true, return the directory
  172. containing standard Python library modules; otherwise, return the
  173. directory for site-specific modules.
  174. If 'prefix' is supplied, use it instead of sys.base_prefix or
  175. sys.base_exec_prefix -- i.e., ignore 'plat_specific'.
  176. """
  177. if IS_PYPY and sys.version_info < (3, 8):
  178. # PyPy-specific schema
  179. if prefix is None:
  180. prefix = PREFIX
  181. if standard_lib:
  182. return os.path.join(prefix, "lib-python", sys.version[0])
  183. return os.path.join(prefix, 'site-packages')
  184. early_prefix = prefix
  185. if prefix is None:
  186. if standard_lib:
  187. prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX
  188. else:
  189. prefix = plat_specific and EXEC_PREFIX or PREFIX
  190. if os.name == "posix":
  191. if plat_specific or standard_lib:
  192. # Platform-specific modules (any module from a non-pure-Python
  193. # module distribution) or standard Python library modules.
  194. libdir = getattr(sys, "platlibdir", "lib")
  195. else:
  196. # Pure Python
  197. libdir = "lib"
  198. implementation = 'pypy' if IS_PYPY else 'python'
  199. libpython = os.path.join(prefix, libdir, implementation + get_python_version())
  200. return _posix_lib(standard_lib, libpython, early_prefix, prefix)
  201. elif os.name == "nt":
  202. if standard_lib:
  203. return os.path.join(prefix, "Lib")
  204. else:
  205. return os.path.join(prefix, "Lib", "site-packages")
  206. else:
  207. raise DistutilsPlatformError(
  208. "I don't know where Python installs its library "
  209. "on platform '%s'" % os.name
  210. )
  211. def customize_compiler(compiler): # noqa: C901
  212. """Do any platform-specific customization of a CCompiler instance.
  213. Mainly needed on Unix, so we can plug in the information that
  214. varies across Unices and is stored in Python's Makefile.
  215. """
  216. if compiler.compiler_type == "unix":
  217. if sys.platform == "darwin":
  218. # Perform first-time customization of compiler-related
  219. # config vars on OS X now that we know we need a compiler.
  220. # This is primarily to support Pythons from binary
  221. # installers. The kind and paths to build tools on
  222. # the user system may vary significantly from the system
  223. # that Python itself was built on. Also the user OS
  224. # version and build tools may not support the same set
  225. # of CPU architectures for universal builds.
  226. global _config_vars
  227. # Use get_config_var() to ensure _config_vars is initialized.
  228. if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
  229. import _osx_support
  230. _osx_support.customize_compiler(_config_vars)
  231. _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
  232. (
  233. cc,
  234. cxx,
  235. cflags,
  236. ccshared,
  237. ldshared,
  238. shlib_suffix,
  239. ar,
  240. ar_flags,
  241. ) = get_config_vars(
  242. 'CC',
  243. 'CXX',
  244. 'CFLAGS',
  245. 'CCSHARED',
  246. 'LDSHARED',
  247. 'SHLIB_SUFFIX',
  248. 'AR',
  249. 'ARFLAGS',
  250. )
  251. if 'CC' in os.environ:
  252. newcc = os.environ['CC']
  253. if 'LDSHARED' not in os.environ and ldshared.startswith(cc):
  254. # If CC is overridden, use that as the default
  255. # command for LDSHARED as well
  256. ldshared = newcc + ldshared[len(cc) :]
  257. cc = newcc
  258. if 'CXX' in os.environ:
  259. cxx = os.environ['CXX']
  260. if 'LDSHARED' in os.environ:
  261. ldshared = os.environ['LDSHARED']
  262. if 'CPP' in os.environ:
  263. cpp = os.environ['CPP']
  264. else:
  265. cpp = cc + " -E" # not always
  266. if 'LDFLAGS' in os.environ:
  267. ldshared = ldshared + ' ' + os.environ['LDFLAGS']
  268. if 'CFLAGS' in os.environ:
  269. cflags = cflags + ' ' + os.environ['CFLAGS']
  270. ldshared = ldshared + ' ' + os.environ['CFLAGS']
  271. if 'CPPFLAGS' in os.environ:
  272. cpp = cpp + ' ' + os.environ['CPPFLAGS']
  273. cflags = cflags + ' ' + os.environ['CPPFLAGS']
  274. ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
  275. if 'AR' in os.environ:
  276. ar = os.environ['AR']
  277. if 'ARFLAGS' in os.environ:
  278. archiver = ar + ' ' + os.environ['ARFLAGS']
  279. else:
  280. archiver = ar + ' ' + ar_flags
  281. cc_cmd = cc + ' ' + cflags
  282. compiler.set_executables(
  283. preprocessor=cpp,
  284. compiler=cc_cmd,
  285. compiler_so=cc_cmd + ' ' + ccshared,
  286. compiler_cxx=cxx,
  287. linker_so=ldshared,
  288. linker_exe=cc,
  289. archiver=archiver,
  290. )
  291. if 'RANLIB' in os.environ and compiler.executables.get('ranlib', None):
  292. compiler.set_executables(ranlib=os.environ['RANLIB'])
  293. compiler.shared_lib_extension = shlib_suffix
  294. def get_config_h_filename():
  295. """Return full pathname of installed pyconfig.h file."""
  296. if python_build:
  297. if os.name == "nt":
  298. inc_dir = os.path.join(_sys_home or project_base, "PC")
  299. else:
  300. inc_dir = _sys_home or project_base
  301. return os.path.join(inc_dir, 'pyconfig.h')
  302. else:
  303. return sysconfig.get_config_h_filename()
  304. def get_makefile_filename():
  305. """Return full pathname of installed Makefile from the Python build."""
  306. return sysconfig.get_makefile_filename()
  307. def parse_config_h(fp, g=None):
  308. """Parse a config.h-style file.
  309. A dictionary containing name/value pairs is returned. If an
  310. optional dictionary is passed in as the second argument, it is
  311. used instead of a new dictionary.
  312. """
  313. return sysconfig.parse_config_h(fp, vars=g)
  314. # Regexes needed for parsing Makefile (and similar syntaxes,
  315. # like old-style Setup files).
  316. _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
  317. _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
  318. _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
  319. def parse_makefile(fn, g=None): # noqa: C901
  320. """Parse a Makefile-style file.
  321. A dictionary containing name/value pairs is returned. If an
  322. optional dictionary is passed in as the second argument, it is
  323. used instead of a new dictionary.
  324. """
  325. from distutils.text_file import TextFile
  326. fp = TextFile(
  327. fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape"
  328. )
  329. if g is None:
  330. g = {}
  331. done = {}
  332. notdone = {}
  333. while True:
  334. line = fp.readline()
  335. if line is None: # eof
  336. break
  337. m = _variable_rx.match(line)
  338. if m:
  339. n, v = m.group(1, 2)
  340. v = v.strip()
  341. # `$$' is a literal `$' in make
  342. tmpv = v.replace('$$', '')
  343. if "$" in tmpv:
  344. notdone[n] = v
  345. else:
  346. try:
  347. v = int(v)
  348. except ValueError:
  349. # insert literal `$'
  350. done[n] = v.replace('$$', '$')
  351. else:
  352. done[n] = v
  353. # Variables with a 'PY_' prefix in the makefile. These need to
  354. # be made available without that prefix through sysconfig.
  355. # Special care is needed to ensure that variable expansion works, even
  356. # if the expansion uses the name without a prefix.
  357. renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
  358. # do variable interpolation here
  359. while notdone:
  360. for name in list(notdone):
  361. value = notdone[name]
  362. m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
  363. if m:
  364. n = m.group(1)
  365. found = True
  366. if n in done:
  367. item = str(done[n])
  368. elif n in notdone:
  369. # get it on a subsequent round
  370. found = False
  371. elif n in os.environ:
  372. # do it like make: fall back to environment
  373. item = os.environ[n]
  374. elif n in renamed_variables:
  375. if name.startswith('PY_') and name[3:] in renamed_variables:
  376. item = ""
  377. elif 'PY_' + n in notdone:
  378. found = False
  379. else:
  380. item = str(done['PY_' + n])
  381. else:
  382. done[n] = item = ""
  383. if found:
  384. after = value[m.end() :]
  385. value = value[: m.start()] + item + after
  386. if "$" in after:
  387. notdone[name] = value
  388. else:
  389. try:
  390. value = int(value)
  391. except ValueError:
  392. done[name] = value.strip()
  393. else:
  394. done[name] = value
  395. del notdone[name]
  396. if name.startswith('PY_') and name[3:] in renamed_variables:
  397. name = name[3:]
  398. if name not in done:
  399. done[name] = value
  400. else:
  401. # bogus variable reference; just drop it since we can't deal
  402. del notdone[name]
  403. fp.close()
  404. # strip spurious spaces
  405. for k, v in done.items():
  406. if isinstance(v, str):
  407. done[k] = v.strip()
  408. # save the results in the global dictionary
  409. g.update(done)
  410. return g
  411. def expand_makefile_vars(s, vars):
  412. """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
  413. 'string' according to 'vars' (a dictionary mapping variable names to
  414. values). Variables not present in 'vars' are silently expanded to the
  415. empty string. The variable values in 'vars' should not contain further
  416. variable expansions; if 'vars' is the output of 'parse_makefile()',
  417. you're fine. Returns a variable-expanded version of 's'.
  418. """
  419. # This algorithm does multiple expansion, so if vars['foo'] contains
  420. # "${bar}", it will expand ${foo} to ${bar}, and then expand
  421. # ${bar}... and so forth. This is fine as long as 'vars' comes from
  422. # 'parse_makefile()', which takes care of such expansions eagerly,
  423. # according to make's variable expansion semantics.
  424. while True:
  425. m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
  426. if m:
  427. (beg, end) = m.span()
  428. s = s[0:beg] + vars.get(m.group(1)) + s[end:]
  429. else:
  430. break
  431. return s
  432. _config_vars = None
  433. def get_config_vars(*args):
  434. """With no arguments, return a dictionary of all configuration
  435. variables relevant for the current platform. Generally this includes
  436. everything needed to build extensions and install both pure modules and
  437. extensions. On Unix, this means every variable defined in Python's
  438. installed Makefile; on Windows it's a much smaller set.
  439. With arguments, return a list of values that result from looking up
  440. each argument in the configuration variable dictionary.
  441. """
  442. global _config_vars
  443. if _config_vars is None:
  444. _config_vars = sysconfig.get_config_vars().copy()
  445. py39compat.add_ext_suffix(_config_vars)
  446. if args:
  447. vals = []
  448. for name in args:
  449. vals.append(_config_vars.get(name))
  450. return vals
  451. else:
  452. return _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)