sysconfig.py 17 KB

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