sysconfig.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. if 'RANLIB' in os.environ and 'ranlib' in compiler.executables:
  208. compiler.set_executables(ranlib=os.environ['RANLIB'])
  209. compiler.shared_lib_extension = shlib_suffix
  210. def get_config_h_filename():
  211. """Return full pathname of installed pyconfig.h file."""
  212. if python_build:
  213. if os.name == "nt":
  214. inc_dir = os.path.join(_sys_home or project_base, "PC")
  215. else:
  216. inc_dir = _sys_home or project_base
  217. else:
  218. inc_dir = get_python_inc(plat_specific=1)
  219. return os.path.join(inc_dir, 'pyconfig.h')
  220. def get_makefile_filename():
  221. """Return full pathname of installed Makefile from the Python build."""
  222. if python_build:
  223. return os.path.join(_sys_home or project_base, "Makefile")
  224. lib_dir = get_python_lib(plat_specific=0, standard_lib=1)
  225. config_file = 'config-{}{}'.format(get_python_version(), build_flags)
  226. if hasattr(sys.implementation, '_multiarch'):
  227. config_file += '-%s' % sys.implementation._multiarch
  228. return os.path.join(lib_dir, config_file, 'Makefile')
  229. def parse_config_h(fp, g=None):
  230. """Parse a config.h-style file.
  231. A dictionary containing name/value pairs is returned. If an
  232. optional dictionary is passed in as the second argument, it is
  233. used instead of a new dictionary.
  234. """
  235. if g is None:
  236. g = {}
  237. define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
  238. undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
  239. #
  240. while True:
  241. line = fp.readline()
  242. if not line:
  243. break
  244. m = define_rx.match(line)
  245. if m:
  246. n, v = m.group(1, 2)
  247. try: v = int(v)
  248. except ValueError: pass
  249. g[n] = v
  250. else:
  251. m = undef_rx.match(line)
  252. if m:
  253. g[m.group(1)] = 0
  254. return g
  255. # Regexes needed for parsing Makefile (and similar syntaxes,
  256. # like old-style Setup files).
  257. _variable_rx = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
  258. _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
  259. _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
  260. def parse_makefile(fn, g=None):
  261. """Parse a Makefile-style file.
  262. A dictionary containing name/value pairs is returned. If an
  263. optional dictionary is passed in as the second argument, it is
  264. used instead of a new dictionary.
  265. """
  266. from distutils.text_file import TextFile
  267. fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1, errors="surrogateescape")
  268. if g is None:
  269. g = {}
  270. done = {}
  271. notdone = {}
  272. while True:
  273. line = fp.readline()
  274. if line is None: # eof
  275. break
  276. m = _variable_rx.match(line)
  277. if m:
  278. n, v = m.group(1, 2)
  279. v = v.strip()
  280. # `$$' is a literal `$' in make
  281. tmpv = v.replace('$$', '')
  282. if "$" in tmpv:
  283. notdone[n] = v
  284. else:
  285. try:
  286. v = int(v)
  287. except ValueError:
  288. # insert literal `$'
  289. done[n] = v.replace('$$', '$')
  290. else:
  291. done[n] = v
  292. # Variables with a 'PY_' prefix in the makefile. These need to
  293. # be made available without that prefix through sysconfig.
  294. # Special care is needed to ensure that variable expansion works, even
  295. # if the expansion uses the name without a prefix.
  296. renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')
  297. # do variable interpolation here
  298. while notdone:
  299. for name in list(notdone):
  300. value = notdone[name]
  301. m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
  302. if m:
  303. n = m.group(1)
  304. found = True
  305. if n in done:
  306. item = str(done[n])
  307. elif n in notdone:
  308. # get it on a subsequent round
  309. found = False
  310. elif n in os.environ:
  311. # do it like make: fall back to environment
  312. item = os.environ[n]
  313. elif n in renamed_variables:
  314. if name.startswith('PY_') and 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: value = int(value)
  329. except ValueError:
  330. done[name] = value.strip()
  331. else:
  332. done[name] = value
  333. del notdone[name]
  334. if name.startswith('PY_') \
  335. and name[3:] in renamed_variables:
  336. name = name[3:]
  337. if name not in done:
  338. done[name] = value
  339. else:
  340. # bogus variable reference; just drop it since we can't deal
  341. del notdone[name]
  342. fp.close()
  343. # strip spurious spaces
  344. for k, v in done.items():
  345. if isinstance(v, str):
  346. done[k] = v.strip()
  347. # save the results in the global dictionary
  348. g.update(done)
  349. return g
  350. def expand_makefile_vars(s, vars):
  351. """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
  352. 'string' according to 'vars' (a dictionary mapping variable names to
  353. values). Variables not present in 'vars' are silently expanded to the
  354. empty string. The variable values in 'vars' should not contain further
  355. variable expansions; if 'vars' is the output of 'parse_makefile()',
  356. you're fine. Returns a variable-expanded version of 's'.
  357. """
  358. # This algorithm does multiple expansion, so if vars['foo'] contains
  359. # "${bar}", it will expand ${foo} to ${bar}, and then expand
  360. # ${bar}... and so forth. This is fine as long as 'vars' comes from
  361. # 'parse_makefile()', which takes care of such expansions eagerly,
  362. # according to make's variable expansion semantics.
  363. while True:
  364. m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
  365. if m:
  366. (beg, end) = m.span()
  367. s = s[0:beg] + vars.get(m.group(1)) + s[end:]
  368. else:
  369. break
  370. return s
  371. _config_vars = None
  372. def _init_posix():
  373. """Initialize the module as appropriate for POSIX systems."""
  374. # _sysconfigdata is generated at build time, see the sysconfig module
  375. name = os.environ.get('_PYTHON_SYSCONFIGDATA_NAME',
  376. os.environ.get('_CONDA_PYTHON_SYSCONFIGDATA_NAME',
  377. '_sysconfigdata_{abi}_{platform}_{multiarch}'.format(
  378. abi=sys.abiflags,
  379. platform=sys.platform,
  380. multiarch=getattr(sys.implementation, '_multiarch', ''))
  381. )
  382. )
  383. _temp = __import__(name, globals(), locals(), ['build_time_vars'], 0)
  384. build_time_vars = _temp.build_time_vars
  385. global _config_vars
  386. _config_vars = {}
  387. _config_vars.update(build_time_vars)
  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. srcdir = _config_vars.get('srcdir', project_base)
  429. if os.name == 'posix':
  430. if python_build:
  431. # If srcdir is a relative path (typically '.' or '..')
  432. # then it should be interpreted relative to the directory
  433. # containing Makefile.
  434. base = os.path.dirname(get_makefile_filename())
  435. srcdir = os.path.join(base, srcdir)
  436. else:
  437. # srcdir is not meaningful since the installation is
  438. # spread about the filesystem. We choose the
  439. # directory containing the Makefile since we know it
  440. # exists.
  441. srcdir = os.path.dirname(get_makefile_filename())
  442. _config_vars['srcdir'] = os.path.abspath(os.path.normpath(srcdir))
  443. # Convert srcdir into an absolute path if it appears necessary.
  444. # Normally it is relative to the build directory. However, during
  445. # testing, for example, we might be running a non-installed python
  446. # from a different directory.
  447. if python_build and os.name == "posix":
  448. base = project_base
  449. if (not os.path.isabs(_config_vars['srcdir']) and
  450. base != os.getcwd()):
  451. # srcdir is relative and we are not in the same directory
  452. # as the executable. Assume executable is in the build
  453. # directory and make srcdir absolute.
  454. srcdir = os.path.join(base, _config_vars['srcdir'])
  455. _config_vars['srcdir'] = os.path.normpath(srcdir)
  456. # OS X platforms require special customization to handle
  457. # multi-architecture, multi-os-version installers
  458. if sys.platform == 'darwin':
  459. import _osx_support
  460. _osx_support.customize_config_vars(_config_vars)
  461. if args:
  462. vals = []
  463. for name in args:
  464. vals.append(_config_vars.get(name))
  465. return vals
  466. else:
  467. return _config_vars
  468. def get_config_var(name):
  469. """Return the value of a single variable using the dictionary
  470. returned by 'get_config_vars()'. Equivalent to
  471. get_config_vars().get(name)
  472. """
  473. if name == 'SO':
  474. import warnings
  475. warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)
  476. return get_config_vars().get(name)