sysconfig.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. __revision__ = "$Id$"
  11. import os
  12. import re
  13. import string
  14. import sys
  15. from distutils.errors import DistutilsPlatformError
  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. # Path to the base directory of the project. On Windows the binary may
  20. # live in project/PCBuild9. If we're dealing with an x64 Windows build,
  21. # it'll live in project/PCbuild/amd64.
  22. project_base = os.path.dirname(os.path.abspath(sys.executable))
  23. if os.name == "nt" and "pcbuild" in project_base[-8:].lower():
  24. project_base = os.path.abspath(os.path.join(project_base, os.path.pardir))
  25. # PC/VS7.1
  26. if os.name == "nt" and "\\pc\\v" in project_base[-10:].lower():
  27. project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
  28. os.path.pardir))
  29. # PC/AMD64
  30. if os.name == "nt" and "\\pcbuild\\amd64" in project_base[-14:].lower():
  31. project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
  32. os.path.pardir))
  33. # set for cross builds
  34. if "_PYTHON_PROJECT_BASE" in os.environ:
  35. # this is the build directory, at least for posix
  36. project_base = os.path.normpath(os.environ["_PYTHON_PROJECT_BASE"])
  37. # python_build: (Boolean) if true, we're either building Python or
  38. # building an extension with an un-installed Python, so we use
  39. # different (hard-wired) directories.
  40. # Setup.local is available for Makefile builds including VPATH builds,
  41. # Setup.dist is available on Windows
  42. def _python_build():
  43. for fn in ("Setup.dist", "Setup.local"):
  44. if os.path.isfile(os.path.join(project_base, "Modules", fn)):
  45. return True
  46. return False
  47. python_build = _python_build()
  48. def get_python_version():
  49. """Return a string containing the major and minor Python version,
  50. leaving off the patchlevel. Sample return values could be '1.5'
  51. or '2.2'.
  52. """
  53. return sys.version[:3]
  54. def get_python_inc(plat_specific=0, prefix=None):
  55. """Return the directory containing installed Python header files.
  56. If 'plat_specific' is false (the default), this is the path to the
  57. non-platform-specific header files, i.e. Python.h and so on;
  58. otherwise, this is the path to platform-specific header files
  59. (namely pyconfig.h).
  60. If 'prefix' is supplied, use it instead of sys.prefix or
  61. sys.exec_prefix -- i.e., ignore 'plat_specific'.
  62. """
  63. if prefix is None:
  64. prefix = plat_specific and EXEC_PREFIX or PREFIX
  65. if os.name == "posix":
  66. if python_build:
  67. buildir = os.path.dirname(sys.executable)
  68. if plat_specific:
  69. # python.h is located in the buildir
  70. inc_dir = buildir
  71. else:
  72. # the source dir is relative to the buildir
  73. srcdir = os.path.abspath(os.path.join(buildir,
  74. get_config_var('srcdir')))
  75. # Include is located in the srcdir
  76. inc_dir = os.path.join(srcdir, "Include")
  77. return inc_dir
  78. return os.path.join(prefix, "include", "python" + get_python_version())
  79. elif os.name == "nt":
  80. return os.path.join(prefix, "include")
  81. elif os.name == "os2":
  82. return os.path.join(prefix, "Include")
  83. else:
  84. raise DistutilsPlatformError(
  85. "I don't know where Python installs its C header files "
  86. "on platform '%s'" % os.name)
  87. def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
  88. """Return the directory containing the Python library (standard or
  89. site additions).
  90. If 'plat_specific' is true, return the directory containing
  91. platform-specific modules, i.e. any module from a non-pure-Python
  92. module distribution; otherwise, return the platform-shared library
  93. directory. If 'standard_lib' is true, return the directory
  94. containing standard Python library modules; otherwise, return the
  95. directory for site-specific modules.
  96. If 'prefix' is supplied, use it instead of sys.prefix or
  97. sys.exec_prefix -- i.e., ignore 'plat_specific'.
  98. """
  99. if prefix is None:
  100. prefix = plat_specific and EXEC_PREFIX or PREFIX
  101. if os.name == "posix":
  102. if plat_specific or standard_lib:
  103. lib = sys.lib
  104. else:
  105. lib = "lib"
  106. libpython = os.path.join(prefix, lib, "python" + get_python_version())
  107. if standard_lib:
  108. return libpython
  109. else:
  110. return os.path.join(libpython, "site-packages")
  111. elif os.name == "nt":
  112. if standard_lib:
  113. return os.path.join(prefix, "Lib")
  114. else:
  115. if get_python_version() < "2.2":
  116. return prefix
  117. else:
  118. return os.path.join(prefix, "Lib", "site-packages")
  119. elif os.name == "os2":
  120. if standard_lib:
  121. return os.path.join(prefix, "Lib")
  122. else:
  123. return os.path.join(prefix, "Lib", "site-packages")
  124. else:
  125. raise DistutilsPlatformError(
  126. "I don't know where Python installs its library "
  127. "on platform '%s'" % os.name)
  128. def customize_compiler(compiler):
  129. """Do any platform-specific customization of a CCompiler instance.
  130. Mainly needed on Unix, so we can plug in the information that
  131. varies across Unices and is stored in Python's Makefile.
  132. """
  133. if compiler.compiler_type == "unix":
  134. if sys.platform == "darwin":
  135. # Perform first-time customization of compiler-related
  136. # config vars on OS X now that we know we need a compiler.
  137. # This is primarily to support Pythons from binary
  138. # installers. The kind and paths to build tools on
  139. # the user system may vary significantly from the system
  140. # that Python itself was built on. Also the user OS
  141. # version and build tools may not support the same set
  142. # of CPU architectures for universal builds.
  143. global _config_vars
  144. # Use get_config_var() to ensure _config_vars is initialized.
  145. if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
  146. import _osx_support
  147. _osx_support.customize_compiler(_config_vars)
  148. _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
  149. (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \
  150. get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
  151. 'CCSHARED', 'LDSHARED', 'SO', 'AR',
  152. 'ARFLAGS')
  153. if 'CC' in os.environ:
  154. newcc = os.environ['CC']
  155. if (sys.platform == 'darwin'
  156. and 'LDSHARED' not in os.environ
  157. and ldshared.startswith(cc)):
  158. # On OS X, if CC is overridden, use that as the default
  159. # command for LDSHARED as well
  160. ldshared = newcc + ldshared[len(cc):]
  161. cc = newcc
  162. if 'CXX' in os.environ:
  163. cxx = os.environ['CXX']
  164. if 'LDSHARED' in os.environ:
  165. ldshared = os.environ['LDSHARED']
  166. if 'CPP' in os.environ:
  167. cpp = os.environ['CPP']
  168. else:
  169. cpp = cc + " -E" # not always
  170. if 'LDFLAGS' in os.environ:
  171. ldshared = ldshared + ' ' + os.environ['LDFLAGS']
  172. if 'CFLAGS' in os.environ:
  173. cflags = opt + ' ' + os.environ['CFLAGS']
  174. ldshared = ldshared + ' ' + os.environ['CFLAGS']
  175. if 'CPPFLAGS' in os.environ:
  176. cpp = cpp + ' ' + os.environ['CPPFLAGS']
  177. cflags = cflags + ' ' + os.environ['CPPFLAGS']
  178. ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
  179. if 'AR' in os.environ:
  180. ar = os.environ['AR']
  181. if 'ARFLAGS' in os.environ:
  182. archiver = ar + ' ' + os.environ['ARFLAGS']
  183. else:
  184. archiver = ar + ' ' + ar_flags
  185. cc_cmd = cc + ' ' + cflags
  186. compiler.set_executables(
  187. preprocessor=cpp,
  188. compiler=cc_cmd,
  189. compiler_so=cc_cmd + ' ' + ccshared,
  190. compiler_cxx=cxx,
  191. linker_so=ldshared,
  192. linker_exe=cc,
  193. archiver=archiver)
  194. compiler.shared_lib_extension = so_ext
  195. def get_config_h_filename():
  196. """Return full pathname of installed pyconfig.h file."""
  197. if python_build:
  198. if os.name == "nt":
  199. inc_dir = os.path.join(project_base, "PC")
  200. else:
  201. inc_dir = project_base
  202. else:
  203. inc_dir = get_python_inc(plat_specific=1)
  204. if get_python_version() < '2.2':
  205. config_h = 'config.h'
  206. else:
  207. # The name of the config.h file changed in 2.2
  208. config_h = 'pyconfig.h'
  209. return os.path.join(inc_dir, config_h)
  210. def get_makefile_filename():
  211. """Return full pathname of installed Makefile from the Python build."""
  212. if python_build:
  213. return os.path.join(project_base, "Makefile")
  214. lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
  215. return os.path.join(lib_dir, "config", "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 1:
  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)
  255. if g is None:
  256. g = {}
  257. done = {}
  258. notdone = {}
  259. while 1:
  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. # do variable interpolation here
  280. while notdone:
  281. for name in notdone.keys():
  282. value = notdone[name]
  283. m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
  284. if m:
  285. n = m.group(1)
  286. found = True
  287. if n in done:
  288. item = str(done[n])
  289. elif n in notdone:
  290. # get it on a subsequent round
  291. found = False
  292. elif n in os.environ:
  293. # do it like make: fall back to environment
  294. item = os.environ[n]
  295. else:
  296. done[n] = item = ""
  297. if found:
  298. after = value[m.end():]
  299. value = value[:m.start()] + item + after
  300. if "$" in after:
  301. notdone[name] = value
  302. else:
  303. try: value = int(value)
  304. except ValueError:
  305. done[name] = value.strip()
  306. else:
  307. done[name] = value
  308. del notdone[name]
  309. else:
  310. # bogus variable reference; just drop it since we can't deal
  311. del notdone[name]
  312. fp.close()
  313. # strip spurious spaces
  314. for k, v in done.items():
  315. if isinstance(v, str):
  316. done[k] = v.strip()
  317. # save the results in the global dictionary
  318. g.update(done)
  319. return g
  320. def expand_makefile_vars(s, vars):
  321. """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
  322. 'string' according to 'vars' (a dictionary mapping variable names to
  323. values). Variables not present in 'vars' are silently expanded to the
  324. empty string. The variable values in 'vars' should not contain further
  325. variable expansions; if 'vars' is the output of 'parse_makefile()',
  326. you're fine. Returns a variable-expanded version of 's'.
  327. """
  328. # This algorithm does multiple expansion, so if vars['foo'] contains
  329. # "${bar}", it will expand ${foo} to ${bar}, and then expand
  330. # ${bar}... and so forth. This is fine as long as 'vars' comes from
  331. # 'parse_makefile()', which takes care of such expansions eagerly,
  332. # according to make's variable expansion semantics.
  333. while 1:
  334. m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
  335. if m:
  336. (beg, end) = m.span()
  337. s = s[0:beg] + vars.get(m.group(1)) + s[end:]
  338. else:
  339. break
  340. return s
  341. _config_vars = None
  342. def _init_posix():
  343. """Initialize the module as appropriate for POSIX systems."""
  344. # _sysconfigdata is generated at build time, see the sysconfig module
  345. from _sysconfigdata import build_time_vars
  346. global _config_vars
  347. _config_vars = {}
  348. _config_vars.update(build_time_vars)
  349. def _init_nt():
  350. """Initialize the module as appropriate for NT"""
  351. g = {}
  352. # set basic install directories
  353. g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  354. g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  355. # XXX hmmm.. a normal install puts include files here
  356. g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  357. g['SO'] = '.pyd'
  358. g['EXE'] = ".exe"
  359. g['VERSION'] = get_python_version().replace(".", "")
  360. g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
  361. global _config_vars
  362. _config_vars = g
  363. def _init_os2():
  364. """Initialize the module as appropriate for OS/2"""
  365. g = {}
  366. # set basic install directories
  367. g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  368. g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  369. # XXX hmmm.. a normal install puts include files here
  370. g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  371. g['SO'] = '.pyd'
  372. g['EXE'] = ".exe"
  373. global _config_vars
  374. _config_vars = g
  375. def get_config_vars(*args):
  376. """With no arguments, return a dictionary of all configuration
  377. variables relevant for the current platform. Generally this includes
  378. everything needed to build extensions and install both pure modules and
  379. extensions. On Unix, this means every variable defined in Python's
  380. installed Makefile; on Windows and Mac OS it's a much smaller set.
  381. With arguments, return a list of values that result from looking up
  382. each argument in the configuration variable dictionary.
  383. """
  384. global _config_vars
  385. if _config_vars is None:
  386. func = globals().get("_init_" + os.name)
  387. if func:
  388. func()
  389. else:
  390. _config_vars = {}
  391. # Normalized versions of prefix and exec_prefix are handy to have;
  392. # in fact, these are the standard versions used most places in the
  393. # Distutils.
  394. _config_vars['prefix'] = PREFIX
  395. _config_vars['exec_prefix'] = EXEC_PREFIX
  396. # OS X platforms require special customization to handle
  397. # multi-architecture, multi-os-version installers
  398. if sys.platform == 'darwin':
  399. import _osx_support
  400. _osx_support.customize_config_vars(_config_vars)
  401. if args:
  402. vals = []
  403. for name in args:
  404. vals.append(_config_vars.get(name))
  405. return vals
  406. else:
  407. return _config_vars
  408. def get_config_var(name):
  409. """Return the value of a single variable using the dictionary
  410. returned by 'get_config_vars()'. Equivalent to
  411. get_config_vars().get(name)
  412. """
  413. return get_config_vars().get(name)