sysconfig.py 18 KB

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