david_david

python-sysconfig.py.txt

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