sysconfig.py 20 KB

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