1
0

sysconfig.py 21 KB

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