PageRenderTime 42ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

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

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