PageRenderTime 56ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/distutils/sysconfig_cpython.py

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