PageRenderTime 56ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/sysconfig.py

https://bitbucket.org/bukzor/pypy
Python | 687 lines | 627 code | 14 blank | 46 comment | 39 complexity | d42b2b25e7a49cca444c32785feb1256 MD5 | raw file
  1. """Provide access to Python's configuration information.
  2. """
  3. import sys
  4. import os
  5. from os.path import pardir, realpath
  6. _INSTALL_SCHEMES = {
  7. 'posix_prefix': {
  8. 'stdlib': '{base}/lib/python{py_version_short}',
  9. 'platstdlib': '{platbase}/lib/python{py_version_short}',
  10. 'purelib': '{base}/lib/python{py_version_short}/site-packages',
  11. 'platlib': '{platbase}/lib/python{py_version_short}/site-packages',
  12. 'include': '{base}/include/python{py_version_short}',
  13. 'platinclude': '{platbase}/include/python{py_version_short}',
  14. 'scripts': '{base}/bin',
  15. 'data': '{base}',
  16. },
  17. 'posix_home': {
  18. 'stdlib': '{base}/lib/python',
  19. 'platstdlib': '{base}/lib/python',
  20. 'purelib': '{base}/lib/python',
  21. 'platlib': '{base}/lib/python',
  22. 'include': '{base}/include/python',
  23. 'platinclude': '{base}/include/python',
  24. 'scripts': '{base}/bin',
  25. 'data' : '{base}',
  26. },
  27. 'nt': {
  28. 'stdlib': '{base}/Lib',
  29. 'platstdlib': '{base}/Lib',
  30. 'purelib': '{base}/Lib/site-packages',
  31. 'platlib': '{base}/Lib/site-packages',
  32. 'include': '{base}/Include',
  33. 'platinclude': '{base}/Include',
  34. 'scripts': '{base}/Scripts',
  35. 'data' : '{base}',
  36. },
  37. 'os2': {
  38. 'stdlib': '{base}/Lib',
  39. 'platstdlib': '{base}/Lib',
  40. 'purelib': '{base}/Lib/site-packages',
  41. 'platlib': '{base}/Lib/site-packages',
  42. 'include': '{base}/Include',
  43. 'platinclude': '{base}/Include',
  44. 'scripts': '{base}/Scripts',
  45. 'data' : '{base}',
  46. },
  47. 'os2_home': {
  48. 'stdlib': '{userbase}/lib/python{py_version_short}',
  49. 'platstdlib': '{userbase}/lib/python{py_version_short}',
  50. 'purelib': '{userbase}/lib/python{py_version_short}/site-packages',
  51. 'platlib': '{userbase}/lib/python{py_version_short}/site-packages',
  52. 'include': '{userbase}/include/python{py_version_short}',
  53. 'scripts': '{userbase}/bin',
  54. 'data' : '{userbase}',
  55. },
  56. 'nt_user': {
  57. 'stdlib': '{userbase}/Python{py_version_nodot}',
  58. 'platstdlib': '{userbase}/Python{py_version_nodot}',
  59. 'purelib': '{userbase}/Python{py_version_nodot}/site-packages',
  60. 'platlib': '{userbase}/Python{py_version_nodot}/site-packages',
  61. 'include': '{userbase}/Python{py_version_nodot}/Include',
  62. 'scripts': '{userbase}/Scripts',
  63. 'data' : '{userbase}',
  64. },
  65. 'posix_user': {
  66. 'stdlib': '{userbase}/lib/python{py_version_short}',
  67. 'platstdlib': '{userbase}/lib/python{py_version_short}',
  68. 'purelib': '{userbase}/lib/python{py_version_short}/site-packages',
  69. 'platlib': '{userbase}/lib/python{py_version_short}/site-packages',
  70. 'include': '{userbase}/include/python{py_version_short}',
  71. 'scripts': '{userbase}/bin',
  72. 'data' : '{userbase}',
  73. },
  74. 'osx_framework_user': {
  75. 'stdlib': '{userbase}/lib/python',
  76. 'platstdlib': '{userbase}/lib/python',
  77. 'purelib': '{userbase}/lib/python/site-packages',
  78. 'platlib': '{userbase}/lib/python/site-packages',
  79. 'include': '{userbase}/include',
  80. 'scripts': '{userbase}/bin',
  81. 'data' : '{userbase}',
  82. },
  83. }
  84. _SCHEME_KEYS = ('stdlib', 'platstdlib', 'purelib', 'platlib', 'include',
  85. 'scripts', 'data')
  86. _PY_VERSION = sys.version.split()[0]
  87. _PY_VERSION_SHORT = sys.version[:3]
  88. _PY_VERSION_SHORT_NO_DOT = _PY_VERSION[0] + _PY_VERSION[2]
  89. _PREFIX = os.path.normpath(sys.prefix)
  90. _EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
  91. _CONFIG_VARS = None
  92. _USER_BASE = None
  93. def _safe_realpath(path):
  94. try:
  95. return realpath(path)
  96. except OSError:
  97. return path
  98. if sys.executable:
  99. _PROJECT_BASE = os.path.dirname(_safe_realpath(sys.executable))
  100. else:
  101. # sys.executable can be empty if argv[0] has been changed and Python is
  102. # unable to retrieve the real program name
  103. _PROJECT_BASE = _safe_realpath(os.getcwd())
  104. if os.name == "nt" and "pcbuild" in _PROJECT_BASE[-8:].lower():
  105. _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir))
  106. # PC/VS7.1
  107. if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower():
  108. _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir))
  109. # PC/AMD64
  110. if os.name == "nt" and "\\pcbuild\\amd64" in _PROJECT_BASE[-14:].lower():
  111. _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir))
  112. def is_python_build():
  113. for fn in ("Setup.dist", "Setup.local"):
  114. if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)):
  115. return True
  116. return False
  117. _PYTHON_BUILD = is_python_build()
  118. if _PYTHON_BUILD:
  119. for scheme in ('posix_prefix', 'posix_home'):
  120. _INSTALL_SCHEMES[scheme]['include'] = '{projectbase}/Include'
  121. _INSTALL_SCHEMES[scheme]['platinclude'] = '{srcdir}'
  122. def _subst_vars(s, local_vars):
  123. try:
  124. return s.format(**local_vars)
  125. except KeyError:
  126. try:
  127. return s.format(**os.environ)
  128. except KeyError, var:
  129. raise AttributeError('{%s}' % var)
  130. def _extend_dict(target_dict, other_dict):
  131. target_keys = target_dict.keys()
  132. for key, value in other_dict.items():
  133. if key in target_keys:
  134. continue
  135. target_dict[key] = value
  136. def _expand_vars(scheme, vars):
  137. res = {}
  138. if vars is None:
  139. vars = {}
  140. _extend_dict(vars, get_config_vars())
  141. for key, value in _INSTALL_SCHEMES[scheme].items():
  142. if os.name in ('posix', 'nt'):
  143. value = os.path.expanduser(value)
  144. res[key] = os.path.normpath(_subst_vars(value, vars))
  145. return res
  146. def _get_default_scheme():
  147. if os.name == 'posix':
  148. # the default scheme for posix is posix_prefix
  149. return 'posix_prefix'
  150. return os.name
  151. def _getuserbase():
  152. env_base = os.environ.get("PYTHONUSERBASE", None)
  153. def joinuser(*args):
  154. return os.path.expanduser(os.path.join(*args))
  155. # what about 'os2emx', 'riscos' ?
  156. if os.name == "nt":
  157. base = os.environ.get("APPDATA") or "~"
  158. return env_base if env_base else joinuser(base, "Python")
  159. if sys.platform == "darwin":
  160. framework = get_config_var("PYTHONFRAMEWORK")
  161. if framework:
  162. return joinuser("~", "Library", framework, "%d.%d"%(
  163. sys.version_info[:2]))
  164. return env_base if env_base else joinuser("~", ".local")
  165. def _parse_makefile(filename, vars=None):
  166. """Parse a Makefile-style file.
  167. A dictionary containing name/value pairs is returned. If an
  168. optional dictionary is passed in as the second argument, it is
  169. used instead of a new dictionary.
  170. """
  171. import re
  172. # Regexes needed for parsing Makefile (and similar syntaxes,
  173. # like old-style Setup files).
  174. _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
  175. _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
  176. _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
  177. if vars is None:
  178. vars = {}
  179. done = {}
  180. notdone = {}
  181. with open(filename) as f:
  182. lines = f.readlines()
  183. for line in lines:
  184. if line.startswith('#') or line.strip() == '':
  185. continue
  186. m = _variable_rx.match(line)
  187. if m:
  188. n, v = m.group(1, 2)
  189. v = v.strip()
  190. # `$$' is a literal `$' in make
  191. tmpv = v.replace('$$', '')
  192. if "$" in tmpv:
  193. notdone[n] = v
  194. else:
  195. try:
  196. v = int(v)
  197. except ValueError:
  198. # insert literal `$'
  199. done[n] = v.replace('$$', '$')
  200. else:
  201. done[n] = v
  202. # do variable interpolation here
  203. while notdone:
  204. for name in notdone.keys():
  205. value = notdone[name]
  206. m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
  207. if m:
  208. n = m.group(1)
  209. found = True
  210. if n in done:
  211. item = str(done[n])
  212. elif n in notdone:
  213. # get it on a subsequent round
  214. found = False
  215. elif n in os.environ:
  216. # do it like make: fall back to environment
  217. item = os.environ[n]
  218. else:
  219. done[n] = item = ""
  220. if found:
  221. after = value[m.end():]
  222. value = value[:m.start()] + item + after
  223. if "$" in after:
  224. notdone[name] = value
  225. else:
  226. try: value = int(value)
  227. except ValueError:
  228. done[name] = value.strip()
  229. else:
  230. done[name] = value
  231. del notdone[name]
  232. else:
  233. # bogus variable reference; just drop it since we can't deal
  234. del notdone[name]
  235. # strip spurious spaces
  236. for k, v in done.items():
  237. if isinstance(v, str):
  238. done[k] = v.strip()
  239. # save the results in the global dictionary
  240. vars.update(done)
  241. return vars
  242. def _get_makefile_filename():
  243. if _PYTHON_BUILD:
  244. return os.path.join(_PROJECT_BASE, "Makefile")
  245. return os.path.join(get_path('platstdlib'), "config", "Makefile")
  246. def _init_posix(vars):
  247. """Initialize the module as appropriate for POSIX systems."""
  248. # load the installed Makefile:
  249. makefile = _get_makefile_filename()
  250. try:
  251. _parse_makefile(makefile, vars)
  252. except IOError, e:
  253. msg = "invalid Python installation: unable to open %s" % makefile
  254. if hasattr(e, "strerror"):
  255. msg = msg + " (%s)" % e.strerror
  256. raise IOError(msg)
  257. # load the installed pyconfig.h:
  258. config_h = get_config_h_filename()
  259. try:
  260. with open(config_h) as f:
  261. parse_config_h(f, vars)
  262. except IOError, e:
  263. msg = "invalid Python installation: unable to open %s" % config_h
  264. if hasattr(e, "strerror"):
  265. msg = msg + " (%s)" % e.strerror
  266. raise IOError(msg)
  267. # On AIX, there are wrong paths to the linker scripts in the Makefile
  268. # -- these paths are relative to the Python source, but when installed
  269. # the scripts are in another directory.
  270. if _PYTHON_BUILD:
  271. vars['LDSHARED'] = vars['BLDSHARED']
  272. def _init_non_posix(vars):
  273. """Initialize the module as appropriate for NT"""
  274. # set basic install directories
  275. vars['LIBDEST'] = get_path('stdlib')
  276. vars['BINLIBDEST'] = get_path('platstdlib')
  277. vars['INCLUDEPY'] = get_path('include')
  278. vars['SO'] = '.pyd'
  279. vars['EXE'] = '.exe'
  280. vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT
  281. vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
  282. #
  283. # public APIs
  284. #
  285. def parse_config_h(fp, vars=None):
  286. """Parse a config.h-style file.
  287. A dictionary containing name/value pairs is returned. If an
  288. optional dictionary is passed in as the second argument, it is
  289. used instead of a new dictionary.
  290. """
  291. import re
  292. if vars is None:
  293. vars = {}
  294. define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
  295. undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
  296. while True:
  297. line = fp.readline()
  298. if not line:
  299. break
  300. m = define_rx.match(line)
  301. if m:
  302. n, v = m.group(1, 2)
  303. try: v = int(v)
  304. except ValueError: pass
  305. vars[n] = v
  306. else:
  307. m = undef_rx.match(line)
  308. if m:
  309. vars[m.group(1)] = 0
  310. return vars
  311. def get_config_h_filename():
  312. """Returns the path of pyconfig.h."""
  313. if _PYTHON_BUILD:
  314. if os.name == "nt":
  315. inc_dir = os.path.join(_PROJECT_BASE, "PC")
  316. else:
  317. inc_dir = _PROJECT_BASE
  318. else:
  319. inc_dir = get_path('platinclude')
  320. return os.path.join(inc_dir, 'pyconfig.h')
  321. def get_scheme_names():
  322. """Returns a tuple containing the schemes names."""
  323. schemes = _INSTALL_SCHEMES.keys()
  324. schemes.sort()
  325. return tuple(schemes)
  326. def get_path_names():
  327. """Returns a tuple containing the paths names."""
  328. return _SCHEME_KEYS
  329. def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
  330. """Returns a mapping containing an install scheme.
  331. ``scheme`` is the install scheme name. If not provided, it will
  332. return the default scheme for the current platform.
  333. """
  334. if expand:
  335. return _expand_vars(scheme, vars)
  336. else:
  337. return _INSTALL_SCHEMES[scheme]
  338. def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
  339. """Returns a path corresponding to the scheme.
  340. ``scheme`` is the install scheme name.
  341. """
  342. return get_paths(scheme, vars, expand)[name]
  343. def get_config_vars(*args):
  344. """With no arguments, return a dictionary of all configuration
  345. variables relevant for the current platform.
  346. On Unix, this means every variable defined in Python's installed Makefile;
  347. On Windows and Mac OS it's a much smaller set.
  348. With arguments, return a list of values that result from looking up
  349. each argument in the configuration variable dictionary.
  350. """
  351. import re
  352. global _CONFIG_VARS
  353. if _CONFIG_VARS is None:
  354. _CONFIG_VARS = {}
  355. # Normalized versions of prefix and exec_prefix are handy to have;
  356. # in fact, these are the standard versions used most places in the
  357. # Distutils.
  358. _CONFIG_VARS['prefix'] = _PREFIX
  359. _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
  360. _CONFIG_VARS['py_version'] = _PY_VERSION
  361. _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
  362. _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2]
  363. _CONFIG_VARS['base'] = _PREFIX
  364. _CONFIG_VARS['platbase'] = _EXEC_PREFIX
  365. _CONFIG_VARS['projectbase'] = _PROJECT_BASE
  366. if os.name in ('nt', 'os2'):
  367. _init_non_posix(_CONFIG_VARS)
  368. if os.name == 'posix':
  369. _init_posix(_CONFIG_VARS)
  370. # Setting 'userbase' is done below the call to the
  371. # init function to enable using 'get_config_var' in
  372. # the init-function.
  373. _CONFIG_VARS['userbase'] = _getuserbase()
  374. if 'srcdir' not in _CONFIG_VARS:
  375. _CONFIG_VARS['srcdir'] = _PROJECT_BASE
  376. # Convert srcdir into an absolute path if it appears necessary.
  377. # Normally it is relative to the build directory. However, during
  378. # testing, for example, we might be running a non-installed python
  379. # from a different directory.
  380. if _PYTHON_BUILD and os.name == "posix":
  381. base = _PROJECT_BASE
  382. try:
  383. cwd = os.getcwd()
  384. except OSError:
  385. cwd = None
  386. if (not os.path.isabs(_CONFIG_VARS['srcdir']) and
  387. base != cwd):
  388. # srcdir is relative and we are not in the same directory
  389. # as the executable. Assume executable is in the build
  390. # directory and make srcdir absolute.
  391. srcdir = os.path.join(base, _CONFIG_VARS['srcdir'])
  392. _CONFIG_VARS['srcdir'] = os.path.normpath(srcdir)
  393. if sys.platform == 'darwin':
  394. kernel_version = os.uname()[2] # Kernel version (8.4.3)
  395. major_version = int(kernel_version.split('.')[0])
  396. if major_version < 8:
  397. # On Mac OS X before 10.4, check if -arch and -isysroot
  398. # are in CFLAGS or LDFLAGS and remove them if they are.
  399. # This is needed when building extensions on a 10.3 system
  400. # using a universal build of python.
  401. for key in ('LDFLAGS', 'BASECFLAGS',
  402. # a number of derived variables. These need to be
  403. # patched up as well.
  404. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
  405. flags = _CONFIG_VARS[key]
  406. flags = re.sub('-arch\s+\w+\s', ' ', flags)
  407. flags = re.sub('-isysroot [^ \t]*', ' ', flags)
  408. _CONFIG_VARS[key] = flags
  409. else:
  410. # Allow the user to override the architecture flags using
  411. # an environment variable.
  412. # NOTE: This name was introduced by Apple in OSX 10.5 and
  413. # is used by several scripting languages distributed with
  414. # that OS release.
  415. if 'ARCHFLAGS' in os.environ:
  416. arch = os.environ['ARCHFLAGS']
  417. for key in ('LDFLAGS', 'BASECFLAGS',
  418. # a number of derived variables. These need to be
  419. # patched up as well.
  420. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
  421. flags = _CONFIG_VARS[key]
  422. flags = re.sub('-arch\s+\w+\s', ' ', flags)
  423. flags = flags + ' ' + arch
  424. _CONFIG_VARS[key] = flags
  425. # If we're on OSX 10.5 or later and the user tries to
  426. # compiles an extension using an SDK that is not present
  427. # on the current machine it is better to not use an SDK
  428. # than to fail.
  429. #
  430. # The major usecase for this is users using a Python.org
  431. # binary installer on OSX 10.6: that installer uses
  432. # the 10.4u SDK, but that SDK is not installed by default
  433. # when you install Xcode.
  434. #
  435. CFLAGS = _CONFIG_VARS.get('CFLAGS', '')
  436. m = re.search('-isysroot\s+(\S+)', CFLAGS)
  437. if m is not None:
  438. sdk = m.group(1)
  439. if not os.path.exists(sdk):
  440. for key in ('LDFLAGS', 'BASECFLAGS',
  441. # a number of derived variables. These need to be
  442. # patched up as well.
  443. 'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
  444. flags = _CONFIG_VARS[key]
  445. flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
  446. _CONFIG_VARS[key] = flags
  447. if args:
  448. vals = []
  449. for name in args:
  450. vals.append(_CONFIG_VARS.get(name))
  451. return vals
  452. else:
  453. return _CONFIG_VARS
  454. def get_config_var(name):
  455. """Return the value of a single variable using the dictionary returned by
  456. 'get_config_vars()'.
  457. Equivalent to get_config_vars().get(name)
  458. """
  459. return get_config_vars().get(name)
  460. def get_platform():
  461. """Return a string that identifies the current platform.
  462. This is used mainly to distinguish platform-specific build directories and
  463. platform-specific built distributions. Typically includes the OS name
  464. and version and the architecture (as supplied by 'os.uname()'),
  465. although the exact information included depends on the OS; eg. for IRIX
  466. the architecture isn't particularly important (IRIX only runs on SGI
  467. hardware), but for Linux the kernel version isn't particularly
  468. important.
  469. Examples of returned values:
  470. linux-i586
  471. linux-alpha (?)
  472. solaris-2.6-sun4u
  473. irix-5.3
  474. irix64-6.2
  475. Windows will return one of:
  476. win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)
  477. win-ia64 (64bit Windows on Itanium)
  478. win32 (all others - specifically, sys.platform is returned)
  479. For other non-POSIX platforms, currently just returns 'sys.platform'.
  480. """
  481. import re
  482. if os.name == 'nt':
  483. # sniff sys.version for architecture.
  484. prefix = " bit ("
  485. i = sys.version.find(prefix)
  486. if i == -1:
  487. return sys.platform
  488. j = sys.version.find(")", i)
  489. look = sys.version[i+len(prefix):j].lower()
  490. if look == 'amd64':
  491. return 'win-amd64'
  492. if look == 'itanium':
  493. return 'win-ia64'
  494. return sys.platform
  495. if os.name != "posix" or not hasattr(os, 'uname'):
  496. # XXX what about the architecture? NT is Intel or Alpha,
  497. # Mac OS is M68k or PPC, etc.
  498. return sys.platform
  499. # Try to distinguish various flavours of Unix
  500. osname, host, release, version, machine = os.uname()
  501. # Convert the OS name to lowercase, remove '/' characters
  502. # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh")
  503. osname = osname.lower().replace('/', '')
  504. machine = machine.replace(' ', '_')
  505. machine = machine.replace('/', '-')
  506. if osname[:5] == "linux":
  507. # At least on Linux/Intel, 'machine' is the processor --
  508. # i386, etc.
  509. # XXX what about Alpha, SPARC, etc?
  510. return "%s-%s" % (osname, machine)
  511. elif osname[:5] == "sunos":
  512. if release[0] >= "5": # SunOS 5 == Solaris 2
  513. osname = "solaris"
  514. release = "%d.%s" % (int(release[0]) - 3, release[2:])
  515. # fall through to standard osname-release-machine representation
  516. elif osname[:4] == "irix": # could be "irix64"!
  517. return "%s-%s" % (osname, release)
  518. elif osname[:3] == "aix":
  519. return "%s-%s.%s" % (osname, version, release)
  520. elif osname[:6] == "cygwin":
  521. osname = "cygwin"
  522. rel_re = re.compile (r'[\d.]+')
  523. m = rel_re.match(release)
  524. if m:
  525. release = m.group()
  526. elif osname[:6] == "darwin":
  527. #
  528. # For our purposes, we'll assume that the system version from
  529. # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set
  530. # to. This makes the compatibility story a bit more sane because the
  531. # machine is going to compile and link as if it were
  532. # MACOSX_DEPLOYMENT_TARGET.
  533. cfgvars = get_config_vars()
  534. macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
  535. if 1:
  536. # Always calculate the release of the running machine,
  537. # needed to determine if we can build fat binaries or not.
  538. macrelease = macver
  539. # Get the system version. Reading this plist is a documented
  540. # way to get the system version (see the documentation for
  541. # the Gestalt Manager)
  542. try:
  543. f = open('/System/Library/CoreServices/SystemVersion.plist')
  544. except IOError:
  545. # We're on a plain darwin box, fall back to the default
  546. # behaviour.
  547. pass
  548. else:
  549. try:
  550. m = re.search(
  551. r'<key>ProductUserVisibleVersion</key>\s*' +
  552. r'<string>(.*?)</string>', f.read())
  553. if m is not None:
  554. macrelease = '.'.join(m.group(1).split('.')[:2])
  555. # else: fall back to the default behaviour
  556. finally:
  557. f.close()
  558. if not macver:
  559. macver = macrelease
  560. if macver:
  561. release = macver
  562. osname = "macosx"
  563. if (macrelease + '.') >= '10.4.' and \
  564. '-arch' in get_config_vars().get('CFLAGS', '').strip():
  565. # The universal build will build fat binaries, but not on
  566. # systems before 10.4
  567. #
  568. # Try to detect 4-way universal builds, those have machine-type
  569. # 'universal' instead of 'fat'.
  570. machine = 'fat'
  571. cflags = get_config_vars().get('CFLAGS')
  572. archs = re.findall('-arch\s+(\S+)', cflags)
  573. archs = tuple(sorted(set(archs)))
  574. if len(archs) == 1:
  575. machine = archs[0]
  576. elif archs == ('i386', 'ppc'):
  577. machine = 'fat'
  578. elif archs == ('i386', 'x86_64'):
  579. machine = 'intel'
  580. elif archs == ('i386', 'ppc', 'x86_64'):
  581. machine = 'fat3'
  582. elif archs == ('ppc64', 'x86_64'):
  583. machine = 'fat64'
  584. elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
  585. machine = 'universal'
  586. else:
  587. raise ValueError(
  588. "Don't know machine value for archs=%r"%(archs,))
  589. elif machine == 'i386':
  590. # On OSX the machine type returned by uname is always the
  591. # 32-bit variant, even if the executable architecture is
  592. # the 64-bit variant
  593. if sys.maxint >= 2**32:
  594. machine = 'x86_64'
  595. elif machine in ('PowerPC', 'Power_Macintosh'):
  596. # Pick a sane name for the PPC architecture.
  597. # See 'i386' case
  598. if sys.maxint >= 2**32:
  599. machine = 'ppc64'
  600. else:
  601. machine = 'ppc'
  602. return "%s-%s-%s" % (osname, release, machine)
  603. def get_python_version():
  604. return _PY_VERSION_SHORT