sysconfig.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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: sysconfig.py 86264 2010-11-06 14:16:30Z eric.araujo $"
  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. # python_build: (Boolean) if true, we're either building Python or
  34. # building an extension with an un-installed Python, so we use
  35. # different (hard-wired) directories.
  36. # Setup.local is available for Makefile builds including VPATH builds,
  37. # Setup.dist is available on Windows
  38. def _python_build():
  39. for fn in ("Setup.dist", "Setup.local"):
  40. if os.path.isfile(os.path.join(project_base, "Modules", fn)):
  41. return True
  42. return False
  43. python_build = _python_build()
  44. def get_python_version():
  45. """Return a string containing the major and minor Python version,
  46. leaving off the patchlevel. Sample return values could be '1.5'
  47. or '2.2'.
  48. """
  49. return sys.version[:3]
  50. def get_python_inc(plat_specific=0, prefix=None):
  51. """Return the directory containing installed Python header files.
  52. If 'plat_specific' is false (the default), this is the path to the
  53. non-platform-specific header files, i.e. Python.h and so on;
  54. otherwise, this is the path to platform-specific header files
  55. (namely pyconfig.h).
  56. If 'prefix' is supplied, use it instead of sys.prefix or
  57. sys.exec_prefix -- i.e., ignore 'plat_specific'.
  58. """
  59. if prefix is None:
  60. prefix = plat_specific and EXEC_PREFIX or PREFIX
  61. prefix = re.sub('host_', 'target_', prefix)
  62. if os.name == "posix":
  63. if python_build:
  64. buildir = re.sub('host_', 'target_', os.path.dirname(sys.executable))
  65. if plat_specific:
  66. # python.h is located in the buildir
  67. inc_dir = buildir
  68. else:
  69. # the source dir is relative to the buildir
  70. srcdir = os.path.abspath(os.path.join(buildir,
  71. get_config_var('srcdir')))
  72. # Include is located in the srcdir
  73. inc_dir = os.path.join(srcdir, "Include")
  74. return inc_dir
  75. return os.path.join(prefix, "include", "python" + get_python_version())
  76. elif os.name == "nt":
  77. return os.path.join(prefix, "include")
  78. elif os.name == "os2":
  79. return os.path.join(prefix, "Include")
  80. else:
  81. raise DistutilsPlatformError(
  82. "I don't know where Python installs its C header files "
  83. "on platform '%s'" % os.name)
  84. def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
  85. """Return the directory containing the Python library (standard or
  86. site additions).
  87. If 'plat_specific' is true, return the directory containing
  88. platform-specific modules, i.e. any module from a non-pure-Python
  89. module distribution; otherwise, return the platform-shared library
  90. directory. If 'standard_lib' is true, return the directory
  91. containing standard Python library modules; otherwise, return the
  92. directory for site-specific modules.
  93. If 'prefix' is supplied, use it instead of sys.prefix or
  94. sys.exec_prefix -- i.e., ignore 'plat_specific'.
  95. """
  96. if prefix is None:
  97. prefix = plat_specific and EXEC_PREFIX or PREFIX
  98. if os.name == "posix":
  99. libpython = os.path.join(prefix,
  100. "lib", "python" + get_python_version())
  101. if standard_lib:
  102. return libpython
  103. else:
  104. return os.path.join(libpython, "site-packages")
  105. elif os.name == "nt":
  106. if standard_lib:
  107. return os.path.join(prefix, "Lib")
  108. else:
  109. if get_python_version() < "2.2":
  110. return prefix
  111. else:
  112. return os.path.join(prefix, "Lib", "site-packages")
  113. elif os.name == "os2":
  114. if standard_lib:
  115. return os.path.join(prefix, "Lib")
  116. else:
  117. return os.path.join(prefix, "Lib", "site-packages")
  118. else:
  119. raise DistutilsPlatformError(
  120. "I don't know where Python installs its library "
  121. "on platform '%s'" % os.name)
  122. def customize_compiler(compiler):
  123. """Do any platform-specific customization of a CCompiler instance.
  124. Mainly needed on Unix, so we can plug in the information that
  125. varies across Unices and is stored in Python's Makefile.
  126. """
  127. if compiler.compiler_type == "unix":
  128. (cc, cxx, opt, cflags, ccshared, ldshared, so_ext) = \
  129. get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
  130. 'CCSHARED', 'LDSHARED', 'SO')
  131. if 'CC' in os.environ:
  132. cc = os.environ['CC']
  133. if 'CXX' in os.environ:
  134. cxx = os.environ['CXX']
  135. if 'LDSHARED' in os.environ:
  136. ldshared = os.environ['LDSHARED']
  137. if 'CPP' in os.environ:
  138. cpp = os.environ['CPP']
  139. else:
  140. cpp = cc + " -E" # not always
  141. if 'LDFLAGS' in os.environ:
  142. ldshared = ldshared + ' ' + os.environ['LDFLAGS']
  143. if 'CFLAGS' in os.environ:
  144. cflags = opt + ' ' + os.environ['CFLAGS']
  145. ldshared = ldshared + ' ' + os.environ['CFLAGS']
  146. if 'CPPFLAGS' in os.environ:
  147. cpp = cpp + ' ' + os.environ['CPPFLAGS']
  148. cflags = cflags + ' ' + os.environ['CPPFLAGS']
  149. ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
  150. cc_cmd = cc + ' ' + cflags
  151. compiler.set_executables(
  152. preprocessor=cpp,
  153. compiler=cc_cmd,
  154. compiler_so=cc_cmd + ' ' + ccshared,
  155. compiler_cxx=cxx,
  156. linker_so=ldshared,
  157. linker_exe=cc)
  158. compiler.shared_lib_extension = so_ext
  159. def get_config_h_filename():
  160. """Return full pathname of installed pyconfig.h file."""
  161. if python_build:
  162. if os.name == "nt":
  163. inc_dir = os.path.join(project_base, "PC")
  164. else:
  165. inc_dir = project_base
  166. else:
  167. inc_dir = get_python_inc(plat_specific=1)
  168. if get_python_version() < '2.2':
  169. config_h = 'config.h'
  170. else:
  171. # The name of the config.h file changed in 2.2
  172. config_h = 'pyconfig.h'
  173. return os.path.join(inc_dir, config_h)
  174. def get_makefile_filename():
  175. """Return full pathname of installed Makefile from the Python build."""
  176. if python_build:
  177. return os.path.join(os.path.dirname(sys.executable), "Makefile")
  178. lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
  179. return os.path.join(lib_dir, "config", "Makefile")
  180. def parse_config_h(fp, g=None):
  181. """Parse a config.h-style file.
  182. A dictionary containing name/value pairs is returned. If an
  183. optional dictionary is passed in as the second argument, it is
  184. used instead of a new dictionary.
  185. """
  186. if g is None:
  187. g = {}
  188. define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
  189. undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
  190. #
  191. while 1:
  192. line = fp.readline()
  193. if not line:
  194. break
  195. m = define_rx.match(line)
  196. if m:
  197. n, v = m.group(1, 2)
  198. try: v = int(v)
  199. except ValueError: pass
  200. g[n] = v
  201. else:
  202. m = undef_rx.match(line)
  203. if m:
  204. g[m.group(1)] = 0
  205. return g
  206. # Regexes needed for parsing Makefile (and similar syntaxes,
  207. # like old-style Setup files).
  208. _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
  209. _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
  210. _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
  211. def parse_makefile(fn, g=None):
  212. """Parse a Makefile-style file.
  213. A dictionary containing name/value pairs is returned. If an
  214. optional dictionary is passed in as the second argument, it is
  215. used instead of a new dictionary.
  216. """
  217. from distutils.text_file import TextFile
  218. fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1)
  219. if g is None:
  220. g = {}
  221. done = {}
  222. notdone = {}
  223. while 1:
  224. line = fp.readline()
  225. if line is None: # eof
  226. break
  227. m = _variable_rx.match(line)
  228. if m:
  229. n, v = m.group(1, 2)
  230. v = v.strip()
  231. # `$$' is a literal `$' in make
  232. tmpv = v.replace('$$', '')
  233. if "$" in tmpv:
  234. notdone[n] = v
  235. else:
  236. try:
  237. v = int(v)
  238. except ValueError:
  239. # insert literal `$'
  240. done[n] = v.replace('$$', '$')
  241. else:
  242. done[n] = v
  243. # do variable interpolation here
  244. while notdone:
  245. for name in notdone.keys():
  246. value = notdone[name]
  247. m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
  248. if m:
  249. n = m.group(1)
  250. found = True
  251. if n in done:
  252. item = str(done[n])
  253. elif n in notdone:
  254. # get it on a subsequent round
  255. found = False
  256. elif n in os.environ:
  257. # do it like make: fall back to environment
  258. item = os.environ[n]
  259. else:
  260. done[n] = item = ""
  261. if found:
  262. after = value[m.end():]
  263. value = value[:m.start()] + item + after
  264. if "$" in after:
  265. notdone[name] = value
  266. else:
  267. try: value = int(value)
  268. except ValueError:
  269. done[name] = value.strip()
  270. else:
  271. done[name] = value
  272. del notdone[name]
  273. else:
  274. # bogus variable reference; just drop it since we can't deal
  275. del notdone[name]
  276. fp.close()
  277. # strip spurious spaces
  278. for k, v in done.items():
  279. if isinstance(v, str):
  280. done[k] = v.strip()
  281. # save the results in the global dictionary
  282. g.update(done)
  283. return g
  284. def expand_makefile_vars(s, vars):
  285. """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
  286. 'string' according to 'vars' (a dictionary mapping variable names to
  287. values). Variables not present in 'vars' are silently expanded to the
  288. empty string. The variable values in 'vars' should not contain further
  289. variable expansions; if 'vars' is the output of 'parse_makefile()',
  290. you're fine. Returns a variable-expanded version of 's'.
  291. """
  292. # This algorithm does multiple expansion, so if vars['foo'] contains
  293. # "${bar}", it will expand ${foo} to ${bar}, and then expand
  294. # ${bar}... and so forth. This is fine as long as 'vars' comes from
  295. # 'parse_makefile()', which takes care of such expansions eagerly,
  296. # according to make's variable expansion semantics.
  297. while 1:
  298. m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
  299. if m:
  300. (beg, end) = m.span()
  301. s = s[0:beg] + vars.get(m.group(1)) + s[end:]
  302. else:
  303. break
  304. return s
  305. _config_vars = None
  306. def _init_posix():
  307. """Initialize the module as appropriate for POSIX systems."""
  308. g = {}
  309. # load the installed Makefile:
  310. try:
  311. filename = get_makefile_filename()
  312. parse_makefile(filename, g)
  313. except IOError, msg:
  314. my_msg = "invalid Python installation: unable to open %s" % filename
  315. if hasattr(msg, "strerror"):
  316. my_msg = my_msg + " (%s)" % msg.strerror
  317. raise DistutilsPlatformError(my_msg)
  318. # load the installed pyconfig.h:
  319. try:
  320. filename = get_config_h_filename()
  321. parse_config_h(file(filename), g)
  322. except IOError, msg:
  323. my_msg = "invalid Python installation: unable to open %s" % filename
  324. if hasattr(msg, "strerror"):
  325. my_msg = my_msg + " (%s)" % msg.strerror
  326. raise DistutilsPlatformError(my_msg)
  327. # On MacOSX we need to check the setting of the environment variable
  328. # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so
  329. # it needs to be compatible.
  330. # If it isn't set we set it to the configure-time value
  331. if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g:
  332. cfg_target = g['MACOSX_DEPLOYMENT_TARGET']
  333. cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '')
  334. if cur_target == '':
  335. cur_target = cfg_target
  336. os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target)
  337. elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')):
  338. my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'
  339. % (cur_target, cfg_target))
  340. raise DistutilsPlatformError(my_msg)
  341. # On AIX, there are wrong paths to the linker scripts in the Makefile
  342. # -- these paths are relative to the Python source, but when installed
  343. # the scripts are in another directory.
  344. if python_build:
  345. g['LDSHARED'] = g['BLDSHARED']
  346. elif get_python_version() < '2.1':
  347. # The following two branches are for 1.5.2 compatibility.
  348. if sys.platform == 'aix4': # what about AIX 3.x ?
  349. # Linker script is in the config directory, not in Modules as the
  350. # Makefile says.
  351. python_lib = get_python_lib(standard_lib=1)
  352. ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
  353. python_exp = os.path.join(python_lib, 'config', 'python.exp')
  354. g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp)
  355. elif sys.platform == 'beos':
  356. # Linker script is in the config directory. In the Makefile it is
  357. # relative to the srcdir, which after installation no longer makes
  358. # sense.
  359. python_lib = get_python_lib(standard_lib=1)
  360. linkerscript_path = string.split(g['LDSHARED'])[0]
  361. linkerscript_name = os.path.basename(linkerscript_path)
  362. linkerscript = os.path.join(python_lib, 'config',
  363. linkerscript_name)
  364. # XXX this isn't the right place to do this: adding the Python
  365. # library to the link, if needed, should be in the "build_ext"
  366. # command. (It's also needed for non-MS compilers on Windows, and
  367. # it's taken care of for them by the 'build_ext.get_libraries()'
  368. # method.)
  369. g['LDSHARED'] = ("%s -L%s/lib -lpython%s" %
  370. (linkerscript, PREFIX, get_python_version()))
  371. global _config_vars
  372. _config_vars = g
  373. def _init_nt():
  374. """Initialize the module as appropriate for NT"""
  375. g = {}
  376. # set basic install directories
  377. g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  378. g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  379. # XXX hmmm.. a normal install puts include files here
  380. g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  381. g['SO'] = '.pyd'
  382. g['EXE'] = ".exe"
  383. g['VERSION'] = get_python_version().replace(".", "")
  384. g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
  385. global _config_vars
  386. _config_vars = g
  387. def _init_os2():
  388. """Initialize the module as appropriate for OS/2"""
  389. g = {}
  390. # set basic install directories
  391. g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  392. g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  393. # XXX hmmm.. a normal install puts include files here
  394. g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  395. g['SO'] = '.pyd'
  396. g['EXE'] = ".exe"
  397. global _config_vars
  398. _config_vars = g
  399. def get_config_vars(*args):
  400. """With no arguments, return a dictionary of all configuration
  401. variables relevant for the current platform. Generally this includes
  402. everything needed to build extensions and install both pure modules and
  403. extensions. On Unix, this means every variable defined in Python's
  404. installed Makefile; on Windows and Mac OS it's a much smaller set.
  405. With arguments, return a list of values that result from looking up
  406. each argument in the configuration variable dictionary.
  407. """
  408. global _config_vars
  409. if _config_vars is None:
  410. func = globals().get("_init_" + os.name)
  411. if func:
  412. func()
  413. else:
  414. _config_vars = {}
  415. # Normalized versions of prefix and exec_prefix are handy to have;
  416. # in fact, these are the standard versions used most places in the
  417. # Distutils.
  418. _config_vars['prefix'] = PREFIX
  419. _config_vars['exec_prefix'] = EXEC_PREFIX
  420. if sys.platform == 'darwin':
  421. kernel_version = os.uname()[2] # Kernel version (8.4.3)
  422. major_version = int(kernel_version.split('.')[0])
  423. if major_version < 8:
  424. # On Mac OS X before 10.4, check if -arch and -isysroot
  425. # are in CFLAGS or LDFLAGS and remove them if they are.
  426. # This is needed when building extensions on a 10.3 system
  427. # using a universal build of python.
  428. for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
  429. # a number of derived variables. These need to be
  430. # patched up as well.
  431. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
  432. flags = _config_vars[key]
  433. flags = re.sub('-arch\s+\w+\s', ' ', flags)
  434. flags = re.sub('-isysroot [^ \t]*', ' ', flags)
  435. _config_vars[key] = flags
  436. else:
  437. # Allow the user to override the architecture flags using
  438. # an environment variable.
  439. # NOTE: This name was introduced by Apple in OSX 10.5 and
  440. # is used by several scripting languages distributed with
  441. # that OS release.
  442. if 'ARCHFLAGS' in os.environ:
  443. arch = os.environ['ARCHFLAGS']
  444. for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
  445. # a number of derived variables. These need to be
  446. # patched up as well.
  447. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
  448. flags = _config_vars[key]
  449. flags = re.sub('-arch\s+\w+\s', ' ', flags)
  450. flags = flags + ' ' + arch
  451. _config_vars[key] = flags
  452. # If we're on OSX 10.5 or later and the user tries to
  453. # compiles an extension using an SDK that is not present
  454. # on the current machine it is better to not use an SDK
  455. # than to fail.
  456. #
  457. # The major usecase for this is users using a Python.org
  458. # binary installer on OSX 10.6: that installer uses
  459. # the 10.4u SDK, but that SDK is not installed by default
  460. # when you install Xcode.
  461. #
  462. m = re.search('-isysroot\s+(\S+)', _config_vars['CFLAGS'])
  463. if m is not None:
  464. sdk = m.group(1)
  465. if not os.path.exists(sdk):
  466. for key in ('LDFLAGS', 'BASECFLAGS', 'LDSHARED',
  467. # a number of derived variables. These need to be
  468. # patched up as well.
  469. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
  470. flags = _config_vars[key]
  471. flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
  472. _config_vars[key] = flags
  473. if args:
  474. vals = []
  475. for name in args:
  476. vals.append(_config_vars.get(name))
  477. return vals
  478. else:
  479. return _config_vars
  480. def get_config_var(name):
  481. """Return the value of a single variable using the dictionary
  482. returned by 'get_config_vars()'. Equivalent to
  483. get_config_vars().get(name)
  484. """
  485. return get_config_vars().get(name)