Advertisement
david_david

python-sysconfig.py.txt

Aug 14th, 2015
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.37 KB | None | 0 0
  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.  
  8. Written by: Fred L. Drake, Jr.
  9. Email: <fdrake@acm.org>
  10. """
  11.  
  12. __revision__ = "$Id$"
  13.  
  14. import os
  15. import re
  16. import string
  17. import sys
  18.  
  19. from distutils.errors import DistutilsPlatformError
  20.  
  21. # These are needed in a couple of spots, so just compute them once.
  22. PREFIX = os.path.normpath(sys.prefix)
  23. EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
  24.  
  25. # Path to the base directory of the project. On Windows the binary may
  26. # live in project/PCBuild9. If we're dealing with an x64 Windows build,
  27. # it'll live in project/PCbuild/amd64.
  28. project_base = os.path.dirname(os.path.abspath(sys.executable))
  29. if os.name == "nt" and "pcbuild" in project_base[-8:].lower():
  30. project_base = os.path.abspath(os.path.join(project_base, os.path.pardir))
  31. # PC/VS7.1
  32. if os.name == "nt" and "\\pc\\v" in project_base[-10:].lower():
  33. project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
  34. os.path.pardir))
  35. # PC/AMD64
  36. if os.name == "nt" and "\\pcbuild\\amd64" in project_base[-14:].lower():
  37. project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
  38. os.path.pardir))
  39.  
  40. # set for cross builds
  41. if "_PYTHON_PROJECT_BASE" in os.environ:
  42. # this is the build directory, at least for posix
  43. project_base = os.path.normpath(os.environ["_PYTHON_PROJECT_BASE"])
  44.  
  45. # python_build: (Boolean) if true, we're either building Python or
  46. # building an extension with an un-installed Python, so we use
  47. # different (hard-wired) directories.
  48. # Setup.local is available for Makefile builds including VPATH builds,
  49. # Setup.dist is available on Windows
  50. def _python_build():
  51. for fn in ("Setup.dist", "Setup.local"):
  52. if os.path.isfile(os.path.join(project_base, "Modules", fn)):
  53. return True
  54. return False
  55. python_build = _python_build()
  56.  
  57.  
  58. def get_python_version():
  59. """Return a string containing the major and minor Python version,
  60. leaving off the patchlevel. Sample return values could be '1.5'
  61. or '2.2'.
  62. """
  63. return sys.version[:3]
  64.  
  65.  
  66. def get_python_inc(plat_specific=0, prefix=None):
  67. """Return the directory containing installed Python header files.
  68.  
  69. If 'plat_specific' is false (the default), this is the path to the
  70. non-platform-specific header files, i.e. Python.h and so on;
  71. otherwise, this is the path to platform-specific header files
  72. (namely pyconfig.h).
  73.  
  74. If 'prefix' is supplied, use it instead of sys.prefix or
  75. sys.exec_prefix -- i.e., ignore 'plat_specific'.
  76. """
  77. if prefix is None:
  78. prefix = plat_specific and EXEC_PREFIX or PREFIX
  79.  
  80. if os.name == "posix":
  81. if python_build:
  82. buildir = os.path.dirname(sys.executable)
  83. if plat_specific:
  84. # python.h is located in the buildir
  85. inc_dir = buildir
  86. else:
  87. # the source dir is relative to the buildir
  88. srcdir = os.path.abspath(os.path.join(buildir,
  89. get_config_var('srcdir')))
  90. # Include is located in the srcdir
  91. inc_dir = os.path.join(srcdir, "Include")
  92. return inc_dir
  93. return os.path.join(prefix, "include", "python" + get_python_version())
  94. elif os.name == "nt":
  95. return os.path.join(prefix, "include")
  96. elif os.name == "os2":
  97. return os.path.join(prefix, "Include")
  98. else:
  99. raise DistutilsPlatformError(
  100. "I don't know where Python installs its C header files "
  101. "on platform '%s'" % os.name)
  102.  
  103.  
  104. def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
  105. """Return the directory containing the Python library (standard or
  106. site additions).
  107.  
  108. If 'plat_specific' is true, return the directory containing
  109. platform-specific modules, i.e. any module from a non-pure-Python
  110. module distribution; otherwise, return the platform-shared library
  111. directory. If 'standard_lib' is true, return the directory
  112. containing standard Python library modules; otherwise, return the
  113. directory for site-specific modules.
  114.  
  115. If 'prefix' is supplied, use it instead of sys.prefix or
  116. sys.exec_prefix -- i.e., ignore 'plat_specific'.
  117. """
  118. if prefix is None:
  119. prefix = plat_specific and EXEC_PREFIX or PREFIX
  120.  
  121. if os.name == "posix":
  122. if plat_specific:
  123. lib = sys.lib
  124. else:
  125. lib = 'lib'
  126. libpython = os.path.join(prefix,
  127. lib, "python" + get_python_version())
  128. if standard_lib:
  129. return libpython
  130. else:
  131. return os.path.join(libpython, "site-packages")
  132.  
  133. elif os.name == "nt":
  134. if standard_lib:
  135. return os.path.join(prefix, "Lib")
  136. else:
  137. if get_python_version() < "2.2":
  138. return prefix
  139. else:
  140. return os.path.join(prefix, "Lib", "site-packages")
  141.  
  142. elif os.name == "os2":
  143. if standard_lib:
  144. return os.path.join(prefix, "Lib")
  145. else:
  146. return os.path.join(prefix, "Lib", "site-packages")
  147.  
  148. else:
  149. raise DistutilsPlatformError(
  150. "I don't know where Python installs its library "
  151. "on platform '%s'" % os.name)
  152.  
  153.  
  154.  
  155. def customize_compiler(compiler):
  156. """Do any platform-specific customization of a CCompiler instance.
  157.  
  158. Mainly needed on Unix, so we can plug in the information that
  159. varies across Unices and is stored in Python's Makefile.
  160. """
  161. if compiler.compiler_type == "unix":
  162. if sys.platform == "darwin":
  163. # Perform first-time customization of compiler-related
  164. # config vars on OS X now that we know we need a compiler.
  165. # This is primarily to support Pythons from binary
  166. # installers. The kind and paths to build tools on
  167. # the user system may vary significantly from the system
  168. # that Python itself was built on. Also the user OS
  169. # version and build tools may not support the same set
  170. # of CPU architectures for universal builds.
  171. global _config_vars
  172. # Use get_config_var() to ensure _config_vars is initialized.
  173. if not get_config_var('CUSTOMIZED_OSX_COMPILER'):
  174. import _osx_support
  175. _osx_support.customize_compiler(_config_vars)
  176. _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'
  177.  
  178. (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \
  179. get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',
  180. 'CCSHARED', 'LDSHARED', 'SO', 'AR',
  181. 'ARFLAGS')
  182.  
  183. if 'CC' in os.environ:
  184. newcc = os.environ['CC']
  185. if (sys.platform == 'darwin'
  186. and 'LDSHARED' not in os.environ
  187. and ldshared.startswith(cc)):
  188. # On OS X, if CC is overridden, use that as the default
  189. # command for LDSHARED as well
  190. ldshared = newcc + ldshared[len(cc):]
  191. cc = newcc
  192. if 'CXX' in os.environ:
  193. cxx = os.environ['CXX']
  194. if 'LDSHARED' in os.environ:
  195. ldshared = os.environ['LDSHARED']
  196. if 'CPP' in os.environ:
  197. cpp = os.environ['CPP']
  198. else:
  199. cpp = cc + " -E" # not always
  200. if 'LDFLAGS' in os.environ:
  201. ldshared = ldshared + ' ' + os.environ['LDFLAGS']
  202. if 'CFLAGS' in os.environ:
  203. cflags = opt + ' ' + os.environ['CFLAGS']
  204. ldshared = ldshared + ' ' + os.environ['CFLAGS']
  205. if 'CPPFLAGS' in os.environ:
  206. cpp = cpp + ' ' + os.environ['CPPFLAGS']
  207. cflags = cflags + ' ' + os.environ['CPPFLAGS']
  208. ldshared = ldshared + ' ' + os.environ['CPPFLAGS']
  209. if 'AR' in os.environ:
  210. ar = os.environ['AR']
  211. if 'ARFLAGS' in os.environ:
  212. archiver = ar + ' ' + os.environ['ARFLAGS']
  213. else:
  214. archiver = ar + ' ' + ar_flags
  215.  
  216. cc_cmd = cc + ' ' + cflags
  217. compiler.set_executables(
  218. preprocessor=cpp,
  219. compiler=cc_cmd,
  220. compiler_so=cc_cmd + ' ' + ccshared,
  221. compiler_cxx=cxx,
  222. linker_so=ldshared,
  223. linker_exe=cc,
  224. archiver=archiver)
  225.  
  226. compiler.shared_lib_extension = so_ext
  227.  
  228.  
  229. def get_config_h_filename():
  230. """Return full pathname of installed pyconfig.h file."""
  231. if python_build:
  232. if os.name == "nt":
  233. inc_dir = os.path.join(project_base, "PC")
  234. else:
  235. inc_dir = project_base
  236. else:
  237. prefix = EXEC_PREFIX or PREFIX
  238. inc_dir = os.path.join(prefix, "include", "multiarch-" + sys.arch + "-linux", "python" + sys.version[:3])
  239. if get_python_version() < '2.2':
  240. config_h = 'config.h'
  241. else:
  242. # The name of the config.h file changed in 2.2
  243. config_h = 'pyconfig.h'
  244. return os.path.join(inc_dir, config_h)
  245.  
  246.  
  247. def get_makefile_filename():
  248. """Return full pathname of installed Makefile from the Python build."""
  249. if python_build:
  250. return os.path.join(project_base, "Makefile")
  251. lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
  252. return os.path.join(lib_dir, "config", "Makefile")
  253.  
  254.  
  255. def parse_config_h(fp, g=None):
  256. """Parse a config.h-style file.
  257.  
  258. A dictionary containing name/value pairs is returned. If an
  259. optional dictionary is passed in as the second argument, it is
  260. used instead of a new dictionary.
  261. """
  262. if g is None:
  263. g = {}
  264. define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
  265. undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
  266. #
  267. while 1:
  268. line = fp.readline()
  269. if not line:
  270. break
  271. m = define_rx.match(line)
  272. if m:
  273. n, v = m.group(1, 2)
  274. try: v = int(v)
  275. except ValueError: pass
  276. g[n] = v
  277. else:
  278. m = undef_rx.match(line)
  279. if m:
  280. g[m.group(1)] = 0
  281. return g
  282.  
  283.  
  284. # Regexes needed for parsing Makefile (and similar syntaxes,
  285. # like old-style Setup files).
  286. _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
  287. _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
  288. _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
  289.  
  290. def parse_makefile(fn, g=None):
  291. """Parse a Makefile-style file.
  292.  
  293. A dictionary containing name/value pairs is returned. If an
  294. optional dictionary is passed in as the second argument, it is
  295. used instead of a new dictionary.
  296. """
  297. from distutils.text_file import TextFile
  298. fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1)
  299.  
  300. if g is None:
  301. g = {}
  302. done = {}
  303. notdone = {}
  304.  
  305. while 1:
  306. line = fp.readline()
  307. if line is None: # eof
  308. break
  309. m = _variable_rx.match(line)
  310. if m:
  311. n, v = m.group(1, 2)
  312. v = v.strip()
  313. # `$$' is a literal `$' in make
  314. tmpv = v.replace('$$', '')
  315.  
  316. if "$" in tmpv:
  317. notdone[n] = v
  318. else:
  319. try:
  320. v = int(v)
  321. except ValueError:
  322. # insert literal `$'
  323. done[n] = v.replace('$$', '$')
  324. else:
  325. done[n] = v
  326.  
  327. # do variable interpolation here
  328. while notdone:
  329. for name in notdone.keys():
  330. value = notdone[name]
  331. m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
  332. if m:
  333. n = m.group(1)
  334. found = True
  335. if n in done:
  336. item = str(done[n])
  337. elif n in notdone:
  338. # get it on a subsequent round
  339. found = False
  340. elif n in os.environ:
  341. # do it like make: fall back to environment
  342. item = os.environ[n]
  343. else:
  344. done[n] = item = ""
  345. if found:
  346. after = value[m.end():]
  347. value = value[:m.start()] + item + after
  348. if "$" in after:
  349. notdone[name] = value
  350. else:
  351. try: value = int(value)
  352. except ValueError:
  353. done[name] = value.strip()
  354. else:
  355. done[name] = value
  356. del notdone[name]
  357. else:
  358. # bogus variable reference; just drop it since we can't deal
  359. del notdone[name]
  360.  
  361. fp.close()
  362.  
  363. # strip spurious spaces
  364. for k, v in done.items():
  365. if isinstance(v, str):
  366. done[k] = v.strip()
  367.  
  368. # save the results in the global dictionary
  369. g.update(done)
  370. return g
  371.  
  372.  
  373. def expand_makefile_vars(s, vars):
  374. """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
  375. 'string' according to 'vars' (a dictionary mapping variable names to
  376. values). Variables not present in 'vars' are silently expanded to the
  377. empty string. The variable values in 'vars' should not contain further
  378. variable expansions; if 'vars' is the output of 'parse_makefile()',
  379. you're fine. Returns a variable-expanded version of 's'.
  380. """
  381.  
  382. # This algorithm does multiple expansion, so if vars['foo'] contains
  383. # "${bar}", it will expand ${foo} to ${bar}, and then expand
  384. # ${bar}... and so forth. This is fine as long as 'vars' comes from
  385. # 'parse_makefile()', which takes care of such expansions eagerly,
  386. # according to make's variable expansion semantics.
  387.  
  388. while 1:
  389. m = _findvar1_rx.search(s) or _findvar2_rx.search(s)
  390. if m:
  391. (beg, end) = m.span()
  392. s = s[0:beg] + vars.get(m.group(1)) + s[end:]
  393. else:
  394. break
  395. return s
  396.  
  397.  
  398. _config_vars = None
  399.  
  400. def _init_posix():
  401. """Initialize the module as appropriate for POSIX systems."""
  402. # _sysconfigdata is generated at build time, see the sysconfig module
  403. from _sysconfigdata import build_time_vars
  404. global _config_vars
  405. _config_vars = {}
  406. _config_vars.update(build_time_vars)
  407.  
  408.  
  409. def _init_nt():
  410. """Initialize the module as appropriate for NT"""
  411. g = {}
  412. # set basic install directories
  413. g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  414. g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  415.  
  416. # XXX hmmm.. a normal install puts include files here
  417. g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  418.  
  419. g['SO'] = '.pyd'
  420. g['EXE'] = ".exe"
  421. g['VERSION'] = get_python_version().replace(".", "")
  422. g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
  423.  
  424. global _config_vars
  425. _config_vars = g
  426.  
  427.  
  428. def _init_os2():
  429. """Initialize the module as appropriate for OS/2"""
  430. g = {}
  431. # set basic install directories
  432. g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
  433. g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
  434.  
  435. # XXX hmmm.. a normal install puts include files here
  436. g['INCLUDEPY'] = get_python_inc(plat_specific=0)
  437.  
  438. g['SO'] = '.pyd'
  439. g['EXE'] = ".exe"
  440.  
  441. global _config_vars
  442. _config_vars = g
  443.  
  444.  
  445. def get_config_vars(*args):
  446. """With no arguments, return a dictionary of all configuration
  447. variables relevant for the current platform. Generally this includes
  448. everything needed to build extensions and install both pure modules and
  449. extensions. On Unix, this means every variable defined in Python's
  450. installed Makefile; on Windows and Mac OS it's a much smaller set.
  451.  
  452. With arguments, return a list of values that result from looking up
  453. each argument in the configuration variable dictionary.
  454. """
  455. global _config_vars
  456. if _config_vars is None:
  457. func = globals().get("_init_" + os.name)
  458. if func:
  459. func()
  460. else:
  461. _config_vars = {}
  462.  
  463. # Normalized versions of prefix and exec_prefix are handy to have;
  464. # in fact, these are the standard versions used most places in the
  465. # Distutils.
  466. _config_vars['prefix'] = PREFIX
  467. _config_vars['exec_prefix'] = EXEC_PREFIX
  468.  
  469. # OS X platforms require special customization to handle
  470. # multi-architecture, multi-os-version installers
  471. if sys.platform == 'darwin':
  472. import _osx_support
  473. _osx_support.customize_config_vars(_config_vars)
  474.  
  475. if args:
  476. vals = []
  477. for name in args:
  478. vals.append(_config_vars.get(name))
  479. return vals
  480. else:
  481. return _config_vars
  482.  
  483. def get_config_var(name):
  484. """Return the value of a single variable using the dictionary
  485. returned by 'get_config_vars()'. Equivalent to
  486. get_config_vars().get(name)
  487. """
  488. return get_config_vars().get(name)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement