sysconfig.py 20 KB

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