logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

platform.py (41933B)


  1. #!/usr/bin/env python3
  2. """ This module tries to retrieve as much platform-identifying data as
  3. possible. It makes this information available via function APIs.
  4. If called from the command line, it prints the platform
  5. information concatenated as single string to stdout. The output
  6. format is useable as part of a filename.
  7. """
  8. # This module is maintained by Marc-Andre Lemburg <mal@egenix.com>.
  9. # If you find problems, please submit bug reports/patches via the
  10. # Python bug tracker (http://bugs.python.org) and assign them to "lemburg".
  11. #
  12. # Still needed:
  13. # * support for MS-DOS (PythonDX ?)
  14. # * support for Amiga and other still unsupported platforms running Python
  15. # * support for additional Linux distributions
  16. #
  17. # Many thanks to all those who helped adding platform-specific
  18. # checks (in no particular order):
  19. #
  20. # Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
  21. # Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
  22. # Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
  23. # Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
  24. # Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
  25. # Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter, Steve
  26. # Dower
  27. #
  28. # History:
  29. #
  30. # <see CVS and SVN checkin messages for history>
  31. #
  32. # 1.0.8 - changed Windows support to read version from kernel32.dll
  33. # 1.0.7 - added DEV_NULL
  34. # 1.0.6 - added linux_distribution()
  35. # 1.0.5 - fixed Java support to allow running the module on Jython
  36. # 1.0.4 - added IronPython support
  37. # 1.0.3 - added normalization of Windows system name
  38. # 1.0.2 - added more Windows support
  39. # 1.0.1 - reformatted to make doc.py happy
  40. # 1.0.0 - reformatted a bit and checked into Python CVS
  41. # 0.8.0 - added sys.version parser and various new access
  42. # APIs (python_version(), python_compiler(), etc.)
  43. # 0.7.2 - fixed architecture() to use sizeof(pointer) where available
  44. # 0.7.1 - added support for Caldera OpenLinux
  45. # 0.7.0 - some fixes for WinCE; untabified the source file
  46. # 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
  47. # vms_lib.getsyi() configured
  48. # 0.6.1 - added code to prevent 'uname -p' on platforms which are
  49. # known not to support it
  50. # 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
  51. # did some cleanup of the interfaces - some APIs have changed
  52. # 0.5.5 - fixed another type in the MacOS code... should have
  53. # used more coffee today ;-)
  54. # 0.5.4 - fixed a few typos in the MacOS code
  55. # 0.5.3 - added experimental MacOS support; added better popen()
  56. # workarounds in _syscmd_ver() -- still not 100% elegant
  57. # though
  58. # 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
  59. # return values (the system uname command tends to return
  60. # 'unknown' instead of just leaving the field empty)
  61. # 0.5.1 - included code for slackware dist; added exception handlers
  62. # to cover up situations where platforms don't have os.popen
  63. # (e.g. Mac) or fail on socket.gethostname(); fixed libc
  64. # detection RE
  65. # 0.5.0 - changed the API names referring to system commands to *syscmd*;
  66. # added java_ver(); made syscmd_ver() a private
  67. # API (was system_ver() in previous versions) -- use uname()
  68. # instead; extended the win32_ver() to also return processor
  69. # type information
  70. # 0.4.0 - added win32_ver() and modified the platform() output for WinXX
  71. # 0.3.4 - fixed a bug in _follow_symlinks()
  72. # 0.3.3 - fixed popen() and "file" command invocation bugs
  73. # 0.3.2 - added architecture() API and support for it in platform()
  74. # 0.3.1 - fixed syscmd_ver() RE to support Windows NT
  75. # 0.3.0 - added system alias support
  76. # 0.2.3 - removed 'wince' again... oh well.
  77. # 0.2.2 - added 'wince' to syscmd_ver() supported platforms
  78. # 0.2.1 - added cache logic and changed the platform string format
  79. # 0.2.0 - changed the API to use functions instead of module globals
  80. # since some action take too long to be run on module import
  81. # 0.1.0 - first release
  82. #
  83. # You can always get the latest version of this module at:
  84. #
  85. # http://www.egenix.com/files/python/platform.py
  86. #
  87. # If that URL should fail, try contacting the author.
  88. __copyright__ = """
  89. Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
  90. Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
  91. Permission to use, copy, modify, and distribute this software and its
  92. documentation for any purpose and without fee or royalty is hereby granted,
  93. provided that the above copyright notice appear in all copies and that
  94. both that copyright notice and this permission notice appear in
  95. supporting documentation or portions thereof, including modifications,
  96. that you make.
  97. EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
  98. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  99. FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
  100. INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  101. FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  102. NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  103. WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
  104. """
  105. __version__ = '1.0.8'
  106. import collections
  107. import os
  108. import re
  109. import sys
  110. import subprocess
  111. import functools
  112. import itertools
  113. ### Globals & Constants
  114. # Helper for comparing two version number strings.
  115. # Based on the description of the PHP's version_compare():
  116. # http://php.net/manual/en/function.version-compare.php
  117. _ver_stages = {
  118. # any string not found in this dict, will get 0 assigned
  119. 'dev': 10,
  120. 'alpha': 20, 'a': 20,
  121. 'beta': 30, 'b': 30,
  122. 'c': 40,
  123. 'RC': 50, 'rc': 50,
  124. # number, will get 100 assigned
  125. 'pl': 200, 'p': 200,
  126. }
  127. _component_re = re.compile(r'([0-9]+|[._+-])')
  128. def _comparable_version(version):
  129. result = []
  130. for v in _component_re.split(version):
  131. if v not in '._+-':
  132. try:
  133. v = int(v, 10)
  134. t = 100
  135. except ValueError:
  136. t = _ver_stages.get(v, 0)
  137. result.extend((t, v))
  138. return result
  139. ### Platform specific APIs
  140. _libc_search = re.compile(b'(__libc_init)'
  141. b'|'
  142. b'(GLIBC_([0-9.]+))'
  143. b'|'
  144. br'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)', re.ASCII)
  145. def libc_ver(executable=None, lib='', version='', chunksize=16384):
  146. """ Tries to determine the libc version that the file executable
  147. (which defaults to the Python interpreter) is linked against.
  148. Returns a tuple of strings (lib,version) which default to the
  149. given parameters in case the lookup fails.
  150. Note that the function has intimate knowledge of how different
  151. libc versions add symbols to the executable and thus is probably
  152. only useable for executables compiled using gcc.
  153. The file is read and scanned in chunks of chunksize bytes.
  154. """
  155. if not executable:
  156. try:
  157. ver = os.confstr('CS_GNU_LIBC_VERSION')
  158. # parse 'glibc 2.28' as ('glibc', '2.28')
  159. parts = ver.split(maxsplit=1)
  160. if len(parts) == 2:
  161. return tuple(parts)
  162. except (AttributeError, ValueError, OSError):
  163. # os.confstr() or CS_GNU_LIBC_VERSION value not available
  164. pass
  165. executable = sys.executable
  166. V = _comparable_version
  167. if hasattr(os.path, 'realpath'):
  168. # Python 2.2 introduced os.path.realpath(); it is used
  169. # here to work around problems with Cygwin not being
  170. # able to open symlinks for reading
  171. executable = os.path.realpath(executable)
  172. with open(executable, 'rb') as f:
  173. binary = f.read(chunksize)
  174. pos = 0
  175. while pos < len(binary):
  176. if b'libc' in binary or b'GLIBC' in binary:
  177. m = _libc_search.search(binary, pos)
  178. else:
  179. m = None
  180. if not m or m.end() == len(binary):
  181. chunk = f.read(chunksize)
  182. if chunk:
  183. binary = binary[max(pos, len(binary) - 1000):] + chunk
  184. pos = 0
  185. continue
  186. if not m:
  187. break
  188. libcinit, glibc, glibcversion, so, threads, soversion = [
  189. s.decode('latin1') if s is not None else s
  190. for s in m.groups()]
  191. if libcinit and not lib:
  192. lib = 'libc'
  193. elif glibc:
  194. if lib != 'glibc':
  195. lib = 'glibc'
  196. version = glibcversion
  197. elif V(glibcversion) > V(version):
  198. version = glibcversion
  199. elif so:
  200. if lib != 'glibc':
  201. lib = 'libc'
  202. if soversion and (not version or V(soversion) > V(version)):
  203. version = soversion
  204. if threads and version[-len(threads):] != threads:
  205. version = version + threads
  206. pos = m.end()
  207. return lib, version
  208. def _norm_version(version, build=''):
  209. """ Normalize the version and build strings and return a single
  210. version string using the format major.minor.build (or patchlevel).
  211. """
  212. l = version.split('.')
  213. if build:
  214. l.append(build)
  215. try:
  216. strings = list(map(str, map(int, l)))
  217. except ValueError:
  218. strings = l
  219. version = '.'.join(strings[:3])
  220. return version
  221. _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
  222. r'.*'
  223. r'\[.* ([\d.]+)\])')
  224. # Examples of VER command output:
  225. #
  226. # Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
  227. # Windows XP: Microsoft Windows XP [Version 5.1.2600]
  228. # Windows Vista: Microsoft Windows [Version 6.0.6002]
  229. #
  230. # Note that the "Version" string gets localized on different
  231. # Windows versions.
  232. def _syscmd_ver(system='', release='', version='',
  233. supported_platforms=('win32', 'win16', 'dos')):
  234. """ Tries to figure out the OS version used and returns
  235. a tuple (system, release, version).
  236. It uses the "ver" shell command for this which is known
  237. to exists on Windows, DOS. XXX Others too ?
  238. In case this fails, the given parameters are used as
  239. defaults.
  240. """
  241. if sys.platform not in supported_platforms:
  242. return system, release, version
  243. # Try some common cmd strings
  244. import subprocess
  245. for cmd in ('ver', 'command /c ver', 'cmd /c ver'):
  246. try:
  247. info = subprocess.check_output(cmd,
  248. stdin=subprocess.DEVNULL,
  249. stderr=subprocess.DEVNULL,
  250. text=True,
  251. shell=True)
  252. except (OSError, subprocess.CalledProcessError) as why:
  253. #print('Command %s failed: %s' % (cmd, why))
  254. continue
  255. else:
  256. break
  257. else:
  258. return system, release, version
  259. # Parse the output
  260. info = info.strip()
  261. m = _ver_output.match(info)
  262. if m is not None:
  263. system, release, version = m.groups()
  264. # Strip trailing dots from version and release
  265. if release[-1] == '.':
  266. release = release[:-1]
  267. if version[-1] == '.':
  268. version = version[:-1]
  269. # Normalize the version and build strings (eliminating additional
  270. # zeros)
  271. version = _norm_version(version)
  272. return system, release, version
  273. _WIN32_CLIENT_RELEASES = {
  274. (5, 0): "2000",
  275. (5, 1): "XP",
  276. # Strictly, 5.2 client is XP 64-bit, but platform.py historically
  277. # has always called it 2003 Server
  278. (5, 2): "2003Server",
  279. (5, None): "post2003",
  280. (6, 0): "Vista",
  281. (6, 1): "7",
  282. (6, 2): "8",
  283. (6, 3): "8.1",
  284. (6, None): "post8.1",
  285. (10, 0): "10",
  286. (10, None): "post10",
  287. }
  288. # Server release name lookup will default to client names if necessary
  289. _WIN32_SERVER_RELEASES = {
  290. (5, 2): "2003Server",
  291. (6, 0): "2008Server",
  292. (6, 1): "2008ServerR2",
  293. (6, 2): "2012Server",
  294. (6, 3): "2012ServerR2",
  295. (6, None): "post2012ServerR2",
  296. }
  297. def win32_is_iot():
  298. return win32_edition() in ('IoTUAP', 'NanoServer', 'WindowsCoreHeadless', 'IoTEdgeOS')
  299. def win32_edition():
  300. try:
  301. try:
  302. import winreg
  303. except ImportError:
  304. import _winreg as winreg
  305. except ImportError:
  306. pass
  307. else:
  308. try:
  309. cvkey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion'
  310. with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, cvkey) as key:
  311. return winreg.QueryValueEx(key, 'EditionId')[0]
  312. except OSError:
  313. pass
  314. return None
  315. def win32_ver(release='', version='', csd='', ptype=''):
  316. try:
  317. from sys import getwindowsversion
  318. except ImportError:
  319. return release, version, csd, ptype
  320. winver = getwindowsversion()
  321. try:
  322. major, minor, build = map(int, _syscmd_ver()[2].split('.'))
  323. except ValueError:
  324. major, minor, build = winver.platform_version or winver[:3]
  325. version = '{0}.{1}.{2}'.format(major, minor, build)
  326. release = (_WIN32_CLIENT_RELEASES.get((major, minor)) or
  327. _WIN32_CLIENT_RELEASES.get((major, None)) or
  328. release)
  329. # getwindowsversion() reflect the compatibility mode Python is
  330. # running under, and so the service pack value is only going to be
  331. # valid if the versions match.
  332. if winver[:2] == (major, minor):
  333. try:
  334. csd = 'SP{}'.format(winver.service_pack_major)
  335. except AttributeError:
  336. if csd[:13] == 'Service Pack ':
  337. csd = 'SP' + csd[13:]
  338. # VER_NT_SERVER = 3
  339. if getattr(winver, 'product_type', None) == 3:
  340. release = (_WIN32_SERVER_RELEASES.get((major, minor)) or
  341. _WIN32_SERVER_RELEASES.get((major, None)) or
  342. release)
  343. try:
  344. try:
  345. import winreg
  346. except ImportError:
  347. import _winreg as winreg
  348. except ImportError:
  349. pass
  350. else:
  351. try:
  352. cvkey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion'
  353. with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, cvkey) as key:
  354. ptype = winreg.QueryValueEx(key, 'CurrentType')[0]
  355. except OSError:
  356. pass
  357. return release, version, csd, ptype
  358. def _mac_ver_xml():
  359. fn = '/System/Library/CoreServices/SystemVersion.plist'
  360. if not os.path.exists(fn):
  361. return None
  362. try:
  363. import plistlib
  364. except ImportError:
  365. return None
  366. with open(fn, 'rb') as f:
  367. pl = plistlib.load(f)
  368. release = pl['ProductVersion']
  369. versioninfo = ('', '', '')
  370. machine = os.uname().machine
  371. if machine in ('ppc', 'Power Macintosh'):
  372. # Canonical name
  373. machine = 'PowerPC'
  374. return release, versioninfo, machine
  375. def mac_ver(release='', versioninfo=('', '', ''), machine=''):
  376. """ Get macOS version information and return it as tuple (release,
  377. versioninfo, machine) with versioninfo being a tuple (version,
  378. dev_stage, non_release_version).
  379. Entries which cannot be determined are set to the parameter values
  380. which default to ''. All tuple entries are strings.
  381. """
  382. # First try reading the information from an XML file which should
  383. # always be present
  384. info = _mac_ver_xml()
  385. if info is not None:
  386. return info
  387. # If that also doesn't work return the default values
  388. return release, versioninfo, machine
  389. def _java_getprop(name, default):
  390. from java.lang import System
  391. try:
  392. value = System.getProperty(name)
  393. if value is None:
  394. return default
  395. return value
  396. except AttributeError:
  397. return default
  398. def java_ver(release='', vendor='', vminfo=('', '', ''), osinfo=('', '', '')):
  399. """ Version interface for Jython.
  400. Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being
  401. a tuple (vm_name, vm_release, vm_vendor) and osinfo being a
  402. tuple (os_name, os_version, os_arch).
  403. Values which cannot be determined are set to the defaults
  404. given as parameters (which all default to '').
  405. """
  406. # Import the needed APIs
  407. try:
  408. import java.lang
  409. except ImportError:
  410. return release, vendor, vminfo, osinfo
  411. vendor = _java_getprop('java.vendor', vendor)
  412. release = _java_getprop('java.version', release)
  413. vm_name, vm_release, vm_vendor = vminfo
  414. vm_name = _java_getprop('java.vm.name', vm_name)
  415. vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  416. vm_release = _java_getprop('java.vm.version', vm_release)
  417. vminfo = vm_name, vm_release, vm_vendor
  418. os_name, os_version, os_arch = osinfo
  419. os_arch = _java_getprop('java.os.arch', os_arch)
  420. os_name = _java_getprop('java.os.name', os_name)
  421. os_version = _java_getprop('java.os.version', os_version)
  422. osinfo = os_name, os_version, os_arch
  423. return release, vendor, vminfo, osinfo
  424. ### System name aliasing
  425. def system_alias(system, release, version):
  426. """ Returns (system, release, version) aliased to common
  427. marketing names used for some systems.
  428. It also does some reordering of the information in some cases
  429. where it would otherwise cause confusion.
  430. """
  431. if system == 'SunOS':
  432. # Sun's OS
  433. if release < '5':
  434. # These releases use the old name SunOS
  435. return system, release, version
  436. # Modify release (marketing release = SunOS release - 3)
  437. l = release.split('.')
  438. if l:
  439. try:
  440. major = int(l[0])
  441. except ValueError:
  442. pass
  443. else:
  444. major = major - 3
  445. l[0] = str(major)
  446. release = '.'.join(l)
  447. if release < '6':
  448. system = 'Solaris'
  449. else:
  450. # XXX Whatever the new SunOS marketing name is...
  451. system = 'Solaris'
  452. elif system in ('win32', 'win16'):
  453. # In case one of the other tricks
  454. system = 'Windows'
  455. # bpo-35516: Don't replace Darwin with macOS since input release and
  456. # version arguments can be different than the currently running version.
  457. return system, release, version
  458. ### Various internal helpers
  459. def _platform(*args):
  460. """ Helper to format the platform string in a filename
  461. compatible format e.g. "system-version-machine".
  462. """
  463. # Format the platform string
  464. platform = '-'.join(x.strip() for x in filter(len, args))
  465. # Cleanup some possible filename obstacles...
  466. platform = platform.replace(' ', '_')
  467. platform = platform.replace('/', '-')
  468. platform = platform.replace('\\', '-')
  469. platform = platform.replace(':', '-')
  470. platform = platform.replace(';', '-')
  471. platform = platform.replace('"', '-')
  472. platform = platform.replace('(', '-')
  473. platform = platform.replace(')', '-')
  474. # No need to report 'unknown' information...
  475. platform = platform.replace('unknown', '')
  476. # Fold '--'s and remove trailing '-'
  477. while 1:
  478. cleaned = platform.replace('--', '-')
  479. if cleaned == platform:
  480. break
  481. platform = cleaned
  482. while platform[-1] == '-':
  483. platform = platform[:-1]
  484. return platform
  485. def _node(default=''):
  486. """ Helper to determine the node name of this machine.
  487. """
  488. try:
  489. import socket
  490. except ImportError:
  491. # No sockets...
  492. return default
  493. try:
  494. return socket.gethostname()
  495. except OSError:
  496. # Still not working...
  497. return default
  498. def _follow_symlinks(filepath):
  499. """ In case filepath is a symlink, follow it until a
  500. real file is reached.
  501. """
  502. filepath = os.path.abspath(filepath)
  503. while os.path.islink(filepath):
  504. filepath = os.path.normpath(
  505. os.path.join(os.path.dirname(filepath), os.readlink(filepath)))
  506. return filepath
  507. def _syscmd_file(target, default=''):
  508. """ Interface to the system's file command.
  509. The function uses the -b option of the file command to have it
  510. omit the filename in its output. Follow the symlinks. It returns
  511. default in case the command should fail.
  512. """
  513. if sys.platform in ('dos', 'win32', 'win16'):
  514. # XXX Others too ?
  515. return default
  516. import subprocess
  517. target = _follow_symlinks(target)
  518. # "file" output is locale dependent: force the usage of the C locale
  519. # to get deterministic behavior.
  520. env = dict(os.environ, LC_ALL='C')
  521. try:
  522. # -b: do not prepend filenames to output lines (brief mode)
  523. output = subprocess.check_output(['file', '-b', target],
  524. stderr=subprocess.DEVNULL,
  525. env=env)
  526. except (OSError, subprocess.CalledProcessError):
  527. return default
  528. if not output:
  529. return default
  530. # With the C locale, the output should be mostly ASCII-compatible.
  531. # Decode from Latin-1 to prevent Unicode decode error.
  532. return output.decode('latin-1')
  533. ### Information about the used architecture
  534. # Default values for architecture; non-empty strings override the
  535. # defaults given as parameters
  536. _default_architecture = {
  537. 'win32': ('', 'WindowsPE'),
  538. 'win16': ('', 'Windows'),
  539. 'dos': ('', 'MSDOS'),
  540. }
  541. def architecture(executable=sys.executable, bits='', linkage=''):
  542. """ Queries the given executable (defaults to the Python interpreter
  543. binary) for various architecture information.
  544. Returns a tuple (bits, linkage) which contains information about
  545. the bit architecture and the linkage format used for the
  546. executable. Both values are returned as strings.
  547. Values that cannot be determined are returned as given by the
  548. parameter presets. If bits is given as '', the sizeof(pointer)
  549. (or sizeof(long) on Python version < 1.5.2) is used as
  550. indicator for the supported pointer size.
  551. The function relies on the system's "file" command to do the
  552. actual work. This is available on most if not all Unix
  553. platforms. On some non-Unix platforms where the "file" command
  554. does not exist and the executable is set to the Python interpreter
  555. binary defaults from _default_architecture are used.
  556. """
  557. # Use the sizeof(pointer) as default number of bits if nothing
  558. # else is given as default.
  559. if not bits:
  560. import struct
  561. size = struct.calcsize('P')
  562. bits = str(size * 8) + 'bit'
  563. # Get data from the 'file' system command
  564. if executable:
  565. fileout = _syscmd_file(executable, '')
  566. else:
  567. fileout = ''
  568. if not fileout and \
  569. executable == sys.executable:
  570. # "file" command did not return anything; we'll try to provide
  571. # some sensible defaults then...
  572. if sys.platform in _default_architecture:
  573. b, l = _default_architecture[sys.platform]
  574. if b:
  575. bits = b
  576. if l:
  577. linkage = l
  578. return bits, linkage
  579. if 'executable' not in fileout and 'shared object' not in fileout:
  580. # Format not supported
  581. return bits, linkage
  582. # Bits
  583. if '32-bit' in fileout:
  584. bits = '32bit'
  585. elif '64-bit' in fileout:
  586. bits = '64bit'
  587. # Linkage
  588. if 'ELF' in fileout:
  589. linkage = 'ELF'
  590. elif 'PE' in fileout:
  591. # E.g. Windows uses this format
  592. if 'Windows' in fileout:
  593. linkage = 'WindowsPE'
  594. else:
  595. linkage = 'PE'
  596. elif 'COFF' in fileout:
  597. linkage = 'COFF'
  598. elif 'MS-DOS' in fileout:
  599. linkage = 'MSDOS'
  600. else:
  601. # XXX the A.OUT format also falls under this class...
  602. pass
  603. return bits, linkage
  604. def _get_machine_win32():
  605. # Try to use the PROCESSOR_* environment variables
  606. # available on Win XP and later; see
  607. # http://support.microsoft.com/kb/888731 and
  608. # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
  609. # WOW64 processes mask the native architecture
  610. return (
  611. os.environ.get('PROCESSOR_ARCHITEW6432', '') or
  612. os.environ.get('PROCESSOR_ARCHITECTURE', '')
  613. )
  614. class _Processor:
  615. @classmethod
  616. def get(cls):
  617. func = getattr(cls, f'get_{sys.platform}', cls.from_subprocess)
  618. return func() or ''
  619. def get_win32():
  620. return os.environ.get('PROCESSOR_IDENTIFIER', _get_machine_win32())
  621. def get_OpenVMS():
  622. try:
  623. import vms_lib
  624. except ImportError:
  625. pass
  626. else:
  627. csid, cpu_number = vms_lib.getsyi('SYI$_CPU', 0)
  628. return 'Alpha' if cpu_number >= 128 else 'VAX'
  629. def from_subprocess():
  630. """
  631. Fall back to `uname -p`
  632. """
  633. try:
  634. return subprocess.check_output(
  635. ['uname', '-p'],
  636. stderr=subprocess.DEVNULL,
  637. text=True,
  638. ).strip()
  639. except (OSError, subprocess.CalledProcessError):
  640. pass
  641. def _unknown_as_blank(val):
  642. return '' if val == 'unknown' else val
  643. ### Portable uname() interface
  644. class uname_result(
  645. collections.namedtuple(
  646. "uname_result_base",
  647. "system node release version machine")
  648. ):
  649. """
  650. A uname_result that's largely compatible with a
  651. simple namedtuple except that 'processor' is
  652. resolved late and cached to avoid calling "uname"
  653. except when needed.
  654. """
  655. @functools.cached_property
  656. def processor(self):
  657. return _unknown_as_blank(_Processor.get())
  658. def __iter__(self):
  659. return itertools.chain(
  660. super().__iter__(),
  661. (self.processor,)
  662. )
  663. @classmethod
  664. def _make(cls, iterable):
  665. # override factory to affect length check
  666. num_fields = len(cls._fields)
  667. result = cls.__new__(cls, *iterable)
  668. if len(result) != num_fields + 1:
  669. msg = f'Expected {num_fields} arguments, got {len(result)}'
  670. raise TypeError(msg)
  671. return result
  672. def __getitem__(self, key):
  673. return tuple(self)[key]
  674. def __len__(self):
  675. return len(tuple(iter(self)))
  676. def __reduce__(self):
  677. return uname_result, tuple(self)[:len(self._fields)]
  678. _uname_cache = None
  679. def uname():
  680. """ Fairly portable uname interface. Returns a tuple
  681. of strings (system, node, release, version, machine, processor)
  682. identifying the underlying platform.
  683. Note that unlike the os.uname function this also returns
  684. possible processor information as an additional tuple entry.
  685. Entries which cannot be determined are set to ''.
  686. """
  687. global _uname_cache
  688. if _uname_cache is not None:
  689. return _uname_cache
  690. # Get some infos from the builtin os.uname API...
  691. try:
  692. system, node, release, version, machine = infos = os.uname()
  693. except AttributeError:
  694. system = sys.platform
  695. node = _node()
  696. release = version = machine = ''
  697. infos = ()
  698. if not any(infos):
  699. # uname is not available
  700. # Try win32_ver() on win32 platforms
  701. if system == 'win32':
  702. release, version, csd, ptype = win32_ver()
  703. machine = machine or _get_machine_win32()
  704. # Try the 'ver' system command available on some
  705. # platforms
  706. if not (release and version):
  707. system, release, version = _syscmd_ver(system)
  708. # Normalize system to what win32_ver() normally returns
  709. # (_syscmd_ver() tends to return the vendor name as well)
  710. if system == 'Microsoft Windows':
  711. system = 'Windows'
  712. elif system == 'Microsoft' and release == 'Windows':
  713. # Under Windows Vista and Windows Server 2008,
  714. # Microsoft changed the output of the ver command. The
  715. # release is no longer printed. This causes the
  716. # system and release to be misidentified.
  717. system = 'Windows'
  718. if '6.0' == version[:3]:
  719. release = 'Vista'
  720. else:
  721. release = ''
  722. # In case we still don't know anything useful, we'll try to
  723. # help ourselves
  724. if system in ('win32', 'win16'):
  725. if not version:
  726. if system == 'win32':
  727. version = '32bit'
  728. else:
  729. version = '16bit'
  730. system = 'Windows'
  731. elif system[:4] == 'java':
  732. release, vendor, vminfo, osinfo = java_ver()
  733. system = 'Java'
  734. version = ', '.join(vminfo)
  735. if not version:
  736. version = vendor
  737. # System specific extensions
  738. if system == 'OpenVMS':
  739. # OpenVMS seems to have release and version mixed up
  740. if not release or release == '0':
  741. release = version
  742. version = ''
  743. # normalize name
  744. if system == 'Microsoft' and release == 'Windows':
  745. system = 'Windows'
  746. release = 'Vista'
  747. vals = system, node, release, version, machine
  748. # Replace 'unknown' values with the more portable ''
  749. _uname_cache = uname_result(*map(_unknown_as_blank, vals))
  750. return _uname_cache
  751. ### Direct interfaces to some of the uname() return values
  752. def system():
  753. """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  754. An empty string is returned if the value cannot be determined.
  755. """
  756. return uname().system
  757. def node():
  758. """ Returns the computer's network name (which may not be fully
  759. qualified)
  760. An empty string is returned if the value cannot be determined.
  761. """
  762. return uname().node
  763. def release():
  764. """ Returns the system's release, e.g. '2.2.0' or 'NT'
  765. An empty string is returned if the value cannot be determined.
  766. """
  767. return uname().release
  768. def version():
  769. """ Returns the system's release version, e.g. '#3 on degas'
  770. An empty string is returned if the value cannot be determined.
  771. """
  772. return uname().version
  773. def machine():
  774. """ Returns the machine type, e.g. 'i386'
  775. An empty string is returned if the value cannot be determined.
  776. """
  777. return uname().machine
  778. def processor():
  779. """ Returns the (true) processor name, e.g. 'amdk6'
  780. An empty string is returned if the value cannot be
  781. determined. Note that many platforms do not provide this
  782. information or simply return the same value as for machine(),
  783. e.g. NetBSD does this.
  784. """
  785. return uname().processor
  786. ### Various APIs for extracting information from sys.version
  787. _sys_version_parser = re.compile(
  788. r'([\w.+]+)\s*' # "version<space>"
  789. r'\(#?([^,]+)' # "(#buildno"
  790. r'(?:,\s*([\w ]*)' # ", builddate"
  791. r'(?:,\s*([\w :]*))?)?\)\s*' # ", buildtime)<space>"
  792. r'\[([^\]]+)\]?', re.ASCII) # "[compiler]"
  793. _ironpython_sys_version_parser = re.compile(
  794. r'IronPython\s*'
  795. r'([\d\.]+)'
  796. r'(?: \(([\d\.]+)\))?'
  797. r' on (.NET [\d\.]+)', re.ASCII)
  798. # IronPython covering 2.6 and 2.7
  799. _ironpython26_sys_version_parser = re.compile(
  800. r'([\d.]+)\s*'
  801. r'\(IronPython\s*'
  802. r'[\d.]+\s*'
  803. r'\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'
  804. )
  805. _pypy_sys_version_parser = re.compile(
  806. r'([\w.+]+)\s*'
  807. r'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  808. r'\[PyPy [^\]]+\]?')
  809. _sys_version_cache = {}
  810. def _sys_version(sys_version=None):
  811. """ Returns a parsed version of Python's sys.version as tuple
  812. (name, version, branch, revision, buildno, builddate, compiler)
  813. referring to the Python implementation name, version, branch,
  814. revision, build number, build date/time as string and the compiler
  815. identification string.
  816. Note that unlike the Python sys.version, the returned value
  817. for the Python version will always include the patchlevel (it
  818. defaults to '.0').
  819. The function returns empty strings for tuple entries that
  820. cannot be determined.
  821. sys_version may be given to parse an alternative version
  822. string, e.g. if the version was read from a different Python
  823. interpreter.
  824. """
  825. # Get the Python version
  826. if sys_version is None:
  827. sys_version = sys.version
  828. # Try the cache first
  829. result = _sys_version_cache.get(sys_version, None)
  830. if result is not None:
  831. return result
  832. # Parse it
  833. if 'IronPython' in sys_version:
  834. # IronPython
  835. name = 'IronPython'
  836. if sys_version.startswith('IronPython'):
  837. match = _ironpython_sys_version_parser.match(sys_version)
  838. else:
  839. match = _ironpython26_sys_version_parser.match(sys_version)
  840. if match is None:
  841. raise ValueError(
  842. 'failed to parse IronPython sys.version: %s' %
  843. repr(sys_version))
  844. version, alt_version, compiler = match.groups()
  845. buildno = ''
  846. builddate = ''
  847. elif sys.platform.startswith('java'):
  848. # Jython
  849. name = 'Jython'
  850. match = _sys_version_parser.match(sys_version)
  851. if match is None:
  852. raise ValueError(
  853. 'failed to parse Jython sys.version: %s' %
  854. repr(sys_version))
  855. version, buildno, builddate, buildtime, _ = match.groups()
  856. if builddate is None:
  857. builddate = ''
  858. compiler = sys.platform
  859. elif "PyPy" in sys_version:
  860. # PyPy
  861. name = "PyPy"
  862. match = _pypy_sys_version_parser.match(sys_version)
  863. if match is None:
  864. raise ValueError("failed to parse PyPy sys.version: %s" %
  865. repr(sys_version))
  866. version, buildno, builddate, buildtime = match.groups()
  867. compiler = ""
  868. else:
  869. # CPython
  870. match = _sys_version_parser.match(sys_version)
  871. if match is None:
  872. raise ValueError(
  873. 'failed to parse CPython sys.version: %s' %
  874. repr(sys_version))
  875. version, buildno, builddate, buildtime, compiler = \
  876. match.groups()
  877. name = 'CPython'
  878. if builddate is None:
  879. builddate = ''
  880. elif buildtime:
  881. builddate = builddate + ' ' + buildtime
  882. if hasattr(sys, '_git'):
  883. _, branch, revision = sys._git
  884. elif hasattr(sys, '_mercurial'):
  885. _, branch, revision = sys._mercurial
  886. else:
  887. branch = ''
  888. revision = ''
  889. # Add the patchlevel version if missing
  890. l = version.split('.')
  891. if len(l) == 2:
  892. l.append('0')
  893. version = '.'.join(l)
  894. # Build and cache the result
  895. result = (name, version, branch, revision, buildno, builddate, compiler)
  896. _sys_version_cache[sys_version] = result
  897. return result
  898. def python_implementation():
  899. """ Returns a string identifying the Python implementation.
  900. Currently, the following implementations are identified:
  901. 'CPython' (C implementation of Python),
  902. 'IronPython' (.NET implementation of Python),
  903. 'Jython' (Java implementation of Python),
  904. 'PyPy' (Python implementation of Python).
  905. """
  906. return _sys_version()[0]
  907. def python_version():
  908. """ Returns the Python version as string 'major.minor.patchlevel'
  909. Note that unlike the Python sys.version, the returned value
  910. will always include the patchlevel (it defaults to 0).
  911. """
  912. return _sys_version()[1]
  913. def python_version_tuple():
  914. """ Returns the Python version as tuple (major, minor, patchlevel)
  915. of strings.
  916. Note that unlike the Python sys.version, the returned value
  917. will always include the patchlevel (it defaults to 0).
  918. """
  919. return tuple(_sys_version()[1].split('.'))
  920. def python_branch():
  921. """ Returns a string identifying the Python implementation
  922. branch.
  923. For CPython this is the SCM branch from which the
  924. Python binary was built.
  925. If not available, an empty string is returned.
  926. """
  927. return _sys_version()[2]
  928. def python_revision():
  929. """ Returns a string identifying the Python implementation
  930. revision.
  931. For CPython this is the SCM revision from which the
  932. Python binary was built.
  933. If not available, an empty string is returned.
  934. """
  935. return _sys_version()[3]
  936. def python_build():
  937. """ Returns a tuple (buildno, builddate) stating the Python
  938. build number and date as strings.
  939. """
  940. return _sys_version()[4:6]
  941. def python_compiler():
  942. """ Returns a string identifying the compiler used for compiling
  943. Python.
  944. """
  945. return _sys_version()[6]
  946. ### The Opus Magnum of platform strings :-)
  947. _platform_cache = {}
  948. def platform(aliased=0, terse=0):
  949. """ Returns a single string identifying the underlying platform
  950. with as much useful information as possible (but no more :).
  951. The output is intended to be human readable rather than
  952. machine parseable. It may look different on different
  953. platforms and this is intended.
  954. If "aliased" is true, the function will use aliases for
  955. various platforms that report system names which differ from
  956. their common names, e.g. SunOS will be reported as
  957. Solaris. The system_alias() function is used to implement
  958. this.
  959. Setting terse to true causes the function to return only the
  960. absolute minimum information needed to identify the platform.
  961. """
  962. result = _platform_cache.get((aliased, terse), None)
  963. if result is not None:
  964. return result
  965. # Get uname information and then apply platform specific cosmetics
  966. # to it...
  967. system, node, release, version, machine, processor = uname()
  968. if machine == processor:
  969. processor = ''
  970. if aliased:
  971. system, release, version = system_alias(system, release, version)
  972. if system == 'Darwin':
  973. # macOS (darwin kernel)
  974. macos_release = mac_ver()[0]
  975. if macos_release:
  976. system = 'macOS'
  977. release = macos_release
  978. if system == 'Windows':
  979. # MS platforms
  980. rel, vers, csd, ptype = win32_ver(version)
  981. if terse:
  982. platform = _platform(system, release)
  983. else:
  984. platform = _platform(system, release, version, csd)
  985. elif system in ('Linux',):
  986. # check for libc vs. glibc
  987. libcname, libcversion = libc_ver()
  988. platform = _platform(system, release, machine, processor,
  989. 'with',
  990. libcname+libcversion)
  991. elif system == 'Java':
  992. # Java platforms
  993. r, v, vminfo, (os_name, os_version, os_arch) = java_ver()
  994. if terse or not os_name:
  995. platform = _platform(system, release, version)
  996. else:
  997. platform = _platform(system, release, version,
  998. 'on',
  999. os_name, os_version, os_arch)
  1000. else:
  1001. # Generic handler
  1002. if terse:
  1003. platform = _platform(system, release)
  1004. else:
  1005. bits, linkage = architecture(sys.executable)
  1006. platform = _platform(system, release, machine,
  1007. processor, bits, linkage)
  1008. _platform_cache[(aliased, terse)] = platform
  1009. return platform
  1010. ### freedesktop.org os-release standard
  1011. # https://www.freedesktop.org/software/systemd/man/os-release.html
  1012. # NAME=value with optional quotes (' or "). The regular expression is less
  1013. # strict than shell lexer, but that's ok.
  1014. _os_release_line = re.compile(
  1015. "^(?P<name>[a-zA-Z0-9_]+)=(?P<quote>[\"\']?)(?P<value>.*)(?P=quote)$"
  1016. )
  1017. # unescape five special characters mentioned in the standard
  1018. _os_release_unescape = re.compile(r"\\([\\\$\"\'`])")
  1019. # /etc takes precedence over /usr/lib
  1020. _os_release_candidates = ("/etc/os-release", "/usr/lib/os-release")
  1021. _os_release_cache = None
  1022. def _parse_os_release(lines):
  1023. # These fields are mandatory fields with well-known defaults
  1024. # in pratice all Linux distributions override NAME, ID, and PRETTY_NAME.
  1025. info = {
  1026. "NAME": "Linux",
  1027. "ID": "linux",
  1028. "PRETTY_NAME": "Linux",
  1029. }
  1030. for line in lines:
  1031. mo = _os_release_line.match(line)
  1032. if mo is not None:
  1033. info[mo.group('name')] = _os_release_unescape.sub(
  1034. r"\1", mo.group('value')
  1035. )
  1036. return info
  1037. def freedesktop_os_release():
  1038. """Return operation system identification from freedesktop.org os-release
  1039. """
  1040. global _os_release_cache
  1041. if _os_release_cache is None:
  1042. errno = None
  1043. for candidate in _os_release_candidates:
  1044. try:
  1045. with open(candidate, encoding="utf-8") as f:
  1046. _os_release_cache = _parse_os_release(f)
  1047. break
  1048. except OSError as e:
  1049. errno = e.errno
  1050. else:
  1051. raise OSError(
  1052. errno,
  1053. f"Unable to read files {', '.join(_os_release_candidates)}"
  1054. )
  1055. return _os_release_cache.copy()
  1056. ### Command line interface
  1057. if __name__ == '__main__':
  1058. # Default is to print the aliased verbose platform string
  1059. terse = ('terse' in sys.argv or '--terse' in sys.argv)
  1060. aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
  1061. print(platform(aliased, terse))
  1062. sys.exit(0)