sysconfig.py 20 KB

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