platform.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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 usable 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 functools
  111. import itertools
  112. ### Globals & Constants
  113. # Helper for comparing two version number strings.
  114. # Based on the description of the PHP's version_compare():
  115. # http://php.net/manual/en/function.version-compare.php
  116. _ver_stages = {
  117. # any string not found in this dict, will get 0 assigned
  118. 'dev': 10,
  119. 'alpha': 20, 'a': 20,
  120. 'beta': 30, 'b': 30,
  121. 'c': 40,
  122. 'RC': 50, 'rc': 50,
  123. # number, will get 100 assigned
  124. 'pl': 200, 'p': 200,
  125. }
  126. def _comparable_version(version):
  127. component_re = re.compile(r'([0-9]+|[._+-])')
  128. result = []
  129. for v in component_re.split(version):
  130. if v not in '._+-':
  131. try:
  132. v = int(v, 10)
  133. t = 100
  134. except ValueError:
  135. t = _ver_stages.get(v, 0)
  136. result.extend((t, v))
  137. return result
  138. ### Platform specific APIs
  139. def libc_ver(executable=None, lib='', version='', chunksize=16384):
  140. """ Tries to determine the libc version that the file executable
  141. (which defaults to the Python interpreter) is linked against.
  142. Returns a tuple of strings (lib,version) which default to the
  143. given parameters in case the lookup fails.
  144. Note that the function has intimate knowledge of how different
  145. libc versions add symbols to the executable and thus is probably
  146. only usable for executables compiled using gcc.
  147. The file is read and scanned in chunks of chunksize bytes.
  148. """
  149. if not executable:
  150. try:
  151. ver = os.confstr('CS_GNU_LIBC_VERSION')
  152. # parse 'glibc 2.28' as ('glibc', '2.28')
  153. parts = ver.split(maxsplit=1)
  154. if len(parts) == 2:
  155. return tuple(parts)
  156. except (AttributeError, ValueError, OSError):
  157. # os.confstr() or CS_GNU_LIBC_VERSION value not available
  158. pass
  159. executable = sys.executable
  160. if not executable:
  161. # sys.executable is not set.
  162. return lib, version
  163. libc_search = re.compile(b'(__libc_init)'
  164. b'|'
  165. b'(GLIBC_([0-9.]+))'
  166. b'|'
  167. br'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)', re.ASCII)
  168. V = _comparable_version
  169. # We use os.path.realpath()
  170. # here to work around problems with Cygwin not being
  171. # able to open symlinks for reading
  172. executable = os.path.realpath(executable)
  173. with open(executable, 'rb') as f:
  174. binary = f.read(chunksize)
  175. pos = 0
  176. while pos < len(binary):
  177. if b'libc' in binary or b'GLIBC' in binary:
  178. m = libc_search.search(binary, pos)
  179. else:
  180. m = None
  181. if not m or m.end() == len(binary):
  182. chunk = f.read(chunksize)
  183. if chunk:
  184. binary = binary[max(pos, len(binary) - 1000):] + chunk
  185. pos = 0
  186. continue
  187. if not m:
  188. break
  189. libcinit, glibc, glibcversion, so, threads, soversion = [
  190. s.decode('latin1') if s is not None else s
  191. for s in m.groups()]
  192. if libcinit and not lib:
  193. lib = 'libc'
  194. elif glibc:
  195. if lib != 'glibc':
  196. lib = 'glibc'
  197. version = glibcversion
  198. elif V(glibcversion) > V(version):
  199. version = glibcversion
  200. elif so:
  201. if lib != 'glibc':
  202. lib = 'libc'
  203. if soversion and (not version or V(soversion) > V(version)):
  204. version = soversion
  205. if threads and version[-len(threads):] != threads:
  206. version = version + threads
  207. pos = m.end()
  208. return lib, version
  209. def _norm_version(version, build=''):
  210. """ Normalize the version and build strings and return a single
  211. version string using the format major.minor.build (or patchlevel).
  212. """
  213. l = version.split('.')
  214. if build:
  215. l.append(build)
  216. try:
  217. strings = list(map(str, map(int, l)))
  218. except ValueError:
  219. strings = l
  220. version = '.'.join(strings[:3])
  221. return version
  222. # Examples of VER command output:
  223. #
  224. # Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
  225. # Windows XP: Microsoft Windows XP [Version 5.1.2600]
  226. # Windows Vista: Microsoft Windows [Version 6.0.6002]
  227. #
  228. # Note that the "Version" string gets localized on different
  229. # Windows versions.
  230. def _syscmd_ver(system='', release='', version='',
  231. supported_platforms=('win32', 'win16', 'dos')):
  232. """ Tries to figure out the OS version used and returns
  233. a tuple (system, release, version).
  234. It uses the "ver" shell command for this which is known
  235. to exists on Windows, DOS. XXX Others too ?
  236. In case this fails, the given parameters are used as
  237. defaults.
  238. """
  239. if sys.platform not in supported_platforms:
  240. return system, release, version
  241. # Try some common cmd strings
  242. import subprocess
  243. for cmd in ('ver', 'command /c ver', 'cmd /c ver'):
  244. try:
  245. info = subprocess.check_output(cmd,
  246. stdin=subprocess.DEVNULL,
  247. stderr=subprocess.DEVNULL,
  248. text=True,
  249. encoding="locale",
  250. shell=True)
  251. except (OSError, subprocess.CalledProcessError) as why:
  252. #print('Command %s failed: %s' % (cmd, why))
  253. continue
  254. else:
  255. break
  256. else:
  257. return system, release, version
  258. ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
  259. r'.*'
  260. r'\[.* ([\d.]+)\])')
  261. # Parse the output
  262. info = info.strip()
  263. m = ver_output.match(info)
  264. if m is not None:
  265. system, release, version = m.groups()
  266. # Strip trailing dots from version and release
  267. if release[-1] == '.':
  268. release = release[:-1]
  269. if version[-1] == '.':
  270. version = version[:-1]
  271. # Normalize the version and build strings (eliminating additional
  272. # zeros)
  273. version = _norm_version(version)
  274. return system, release, version
  275. try:
  276. import _wmi
  277. except ImportError:
  278. def _wmi_query(*keys):
  279. raise OSError("not supported")
  280. else:
  281. def _wmi_query(table, *keys):
  282. table = {
  283. "OS": "Win32_OperatingSystem",
  284. "CPU": "Win32_Processor",
  285. }[table]
  286. data = _wmi.exec_query("SELECT {} FROM {}".format(
  287. ",".join(keys),
  288. table,
  289. )).split("\0")
  290. split_data = (i.partition("=") for i in data)
  291. dict_data = {i[0]: i[2] for i in split_data}
  292. return (dict_data[k] for k in keys)
  293. _WIN32_CLIENT_RELEASES = [
  294. ((10, 1, 0), "post11"),
  295. ((10, 0, 22000), "11"),
  296. ((6, 4, 0), "10"),
  297. ((6, 3, 0), "8.1"),
  298. ((6, 2, 0), "8"),
  299. ((6, 1, 0), "7"),
  300. ((6, 0, 0), "Vista"),
  301. ((5, 2, 3790), "XP64"),
  302. ((5, 2, 0), "XPMedia"),
  303. ((5, 1, 0), "XP"),
  304. ((5, 0, 0), "2000"),
  305. ]
  306. _WIN32_SERVER_RELEASES = [
  307. ((10, 1, 0), "post2022Server"),
  308. ((10, 0, 20348), "2022Server"),
  309. ((10, 0, 17763), "2019Server"),
  310. ((6, 4, 0), "2016Server"),
  311. ((6, 3, 0), "2012ServerR2"),
  312. ((6, 2, 0), "2012Server"),
  313. ((6, 1, 0), "2008ServerR2"),
  314. ((6, 0, 0), "2008Server"),
  315. ((5, 2, 0), "2003Server"),
  316. ((5, 0, 0), "2000Server"),
  317. ]
  318. def win32_is_iot():
  319. return win32_edition() in ('IoTUAP', 'NanoServer', 'WindowsCoreHeadless', 'IoTEdgeOS')
  320. def win32_edition():
  321. try:
  322. try:
  323. import winreg
  324. except ImportError:
  325. import _winreg as winreg
  326. except ImportError:
  327. pass
  328. else:
  329. try:
  330. cvkey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion'
  331. with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, cvkey) as key:
  332. return winreg.QueryValueEx(key, 'EditionId')[0]
  333. except OSError:
  334. pass
  335. return None
  336. def _win32_ver(version, csd, ptype):
  337. # Try using WMI first, as this is the canonical source of data
  338. try:
  339. (version, product_type, ptype, spmajor, spminor) = _wmi_query(
  340. 'OS',
  341. 'Version',
  342. 'ProductType',
  343. 'BuildType',
  344. 'ServicePackMajorVersion',
  345. 'ServicePackMinorVersion',
  346. )
  347. is_client = (int(product_type) == 1)
  348. if spminor and spminor != '0':
  349. csd = f'SP{spmajor}.{spminor}'
  350. else:
  351. csd = f'SP{spmajor}'
  352. return version, csd, ptype, is_client
  353. except OSError:
  354. pass
  355. # Fall back to a combination of sys.getwindowsversion and "ver"
  356. try:
  357. from sys import getwindowsversion
  358. except ImportError:
  359. return version, csd, ptype, True
  360. winver = getwindowsversion()
  361. is_client = (getattr(winver, 'product_type', 1) == 1)
  362. try:
  363. version = _syscmd_ver()[2]
  364. major, minor, build = map(int, version.split('.'))
  365. except ValueError:
  366. major, minor, build = winver.platform_version or winver[:3]
  367. version = '{0}.{1}.{2}'.format(major, minor, build)
  368. # getwindowsversion() reflect the compatibility mode Python is
  369. # running under, and so the service pack value is only going to be
  370. # valid if the versions match.
  371. if winver[:2] == (major, minor):
  372. try:
  373. csd = 'SP{}'.format(winver.service_pack_major)
  374. except AttributeError:
  375. if csd[:13] == 'Service Pack ':
  376. csd = 'SP' + csd[13:]
  377. try:
  378. try:
  379. import winreg
  380. except ImportError:
  381. import _winreg as winreg
  382. except ImportError:
  383. pass
  384. else:
  385. try:
  386. cvkey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion'
  387. with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, cvkey) as key:
  388. ptype = winreg.QueryValueEx(key, 'CurrentType')[0]
  389. except OSError:
  390. pass
  391. return version, csd, ptype, is_client
  392. def win32_ver(release='', version='', csd='', ptype=''):
  393. is_client = False
  394. version, csd, ptype, is_client = _win32_ver(version, csd, ptype)
  395. if version:
  396. intversion = tuple(map(int, version.split('.')))
  397. releases = _WIN32_CLIENT_RELEASES if is_client else _WIN32_SERVER_RELEASES
  398. release = next((r for v, r in releases if v <= intversion), release)
  399. return release, version, csd, ptype
  400. def _mac_ver_xml():
  401. fn = '/System/Library/CoreServices/SystemVersion.plist'
  402. if not os.path.exists(fn):
  403. return None
  404. try:
  405. import plistlib
  406. except ImportError:
  407. return None
  408. with open(fn, 'rb') as f:
  409. pl = plistlib.load(f)
  410. release = pl['ProductVersion']
  411. versioninfo = ('', '', '')
  412. machine = os.uname().machine
  413. if machine in ('ppc', 'Power Macintosh'):
  414. # Canonical name
  415. machine = 'PowerPC'
  416. return release, versioninfo, machine
  417. def mac_ver(release='', versioninfo=('', '', ''), machine=''):
  418. """ Get macOS version information and return it as tuple (release,
  419. versioninfo, machine) with versioninfo being a tuple (version,
  420. dev_stage, non_release_version).
  421. Entries which cannot be determined are set to the parameter values
  422. which default to ''. All tuple entries are strings.
  423. """
  424. # First try reading the information from an XML file which should
  425. # always be present
  426. info = _mac_ver_xml()
  427. if info is not None:
  428. return info
  429. # If that also doesn't work return the default values
  430. return release, versioninfo, machine
  431. def _java_getprop(name, default):
  432. from java.lang import System
  433. try:
  434. value = System.getProperty(name)
  435. if value is None:
  436. return default
  437. return value
  438. except AttributeError:
  439. return default
  440. def java_ver(release='', vendor='', vminfo=('', '', ''), osinfo=('', '', '')):
  441. """ Version interface for Jython.
  442. Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being
  443. a tuple (vm_name, vm_release, vm_vendor) and osinfo being a
  444. tuple (os_name, os_version, os_arch).
  445. Values which cannot be determined are set to the defaults
  446. given as parameters (which all default to '').
  447. """
  448. # Import the needed APIs
  449. try:
  450. import java.lang
  451. except ImportError:
  452. return release, vendor, vminfo, osinfo
  453. vendor = _java_getprop('java.vendor', vendor)
  454. release = _java_getprop('java.version', release)
  455. vm_name, vm_release, vm_vendor = vminfo
  456. vm_name = _java_getprop('java.vm.name', vm_name)
  457. vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  458. vm_release = _java_getprop('java.vm.version', vm_release)
  459. vminfo = vm_name, vm_release, vm_vendor
  460. os_name, os_version, os_arch = osinfo
  461. os_arch = _java_getprop('java.os.arch', os_arch)
  462. os_name = _java_getprop('java.os.name', os_name)
  463. os_version = _java_getprop('java.os.version', os_version)
  464. osinfo = os_name, os_version, os_arch
  465. return release, vendor, vminfo, osinfo
  466. ### System name aliasing
  467. def system_alias(system, release, version):
  468. """ Returns (system, release, version) aliased to common
  469. marketing names used for some systems.
  470. It also does some reordering of the information in some cases
  471. where it would otherwise cause confusion.
  472. """
  473. if system == 'SunOS':
  474. # Sun's OS
  475. if release < '5':
  476. # These releases use the old name SunOS
  477. return system, release, version
  478. # Modify release (marketing release = SunOS release - 3)
  479. l = release.split('.')
  480. if l:
  481. try:
  482. major = int(l[0])
  483. except ValueError:
  484. pass
  485. else:
  486. major = major - 3
  487. l[0] = str(major)
  488. release = '.'.join(l)
  489. if release < '6':
  490. system = 'Solaris'
  491. else:
  492. # XXX Whatever the new SunOS marketing name is...
  493. system = 'Solaris'
  494. elif system in ('win32', 'win16'):
  495. # In case one of the other tricks
  496. system = 'Windows'
  497. # bpo-35516: Don't replace Darwin with macOS since input release and
  498. # version arguments can be different than the currently running version.
  499. return system, release, version
  500. ### Various internal helpers
  501. def _platform(*args):
  502. """ Helper to format the platform string in a filename
  503. compatible format e.g. "system-version-machine".
  504. """
  505. # Format the platform string
  506. platform = '-'.join(x.strip() for x in filter(len, args))
  507. # Cleanup some possible filename obstacles...
  508. platform = platform.replace(' ', '_')
  509. platform = platform.replace('/', '-')
  510. platform = platform.replace('\\', '-')
  511. platform = platform.replace(':', '-')
  512. platform = platform.replace(';', '-')
  513. platform = platform.replace('"', '-')
  514. platform = platform.replace('(', '-')
  515. platform = platform.replace(')', '-')
  516. # No need to report 'unknown' information...
  517. platform = platform.replace('unknown', '')
  518. # Fold '--'s and remove trailing '-'
  519. while True:
  520. cleaned = platform.replace('--', '-')
  521. if cleaned == platform:
  522. break
  523. platform = cleaned
  524. while platform[-1] == '-':
  525. platform = platform[:-1]
  526. return platform
  527. def _node(default=''):
  528. """ Helper to determine the node name of this machine.
  529. """
  530. try:
  531. import socket
  532. except ImportError:
  533. # No sockets...
  534. return default
  535. try:
  536. return socket.gethostname()
  537. except OSError:
  538. # Still not working...
  539. return default
  540. def _follow_symlinks(filepath):
  541. """ In case filepath is a symlink, follow it until a
  542. real file is reached.
  543. """
  544. filepath = os.path.abspath(filepath)
  545. while os.path.islink(filepath):
  546. filepath = os.path.normpath(
  547. os.path.join(os.path.dirname(filepath), os.readlink(filepath)))
  548. return filepath
  549. def _syscmd_file(target, default=''):
  550. """ Interface to the system's file command.
  551. The function uses the -b option of the file command to have it
  552. omit the filename in its output. Follow the symlinks. It returns
  553. default in case the command should fail.
  554. """
  555. if sys.platform in ('dos', 'win32', 'win16'):
  556. # XXX Others too ?
  557. return default
  558. try:
  559. import subprocess
  560. except ImportError:
  561. return default
  562. target = _follow_symlinks(target)
  563. # "file" output is locale dependent: force the usage of the C locale
  564. # to get deterministic behavior.
  565. env = dict(os.environ, LC_ALL='C')
  566. try:
  567. # -b: do not prepend filenames to output lines (brief mode)
  568. output = subprocess.check_output(['file', '-b', target],
  569. stderr=subprocess.DEVNULL,
  570. env=env)
  571. except (OSError, subprocess.CalledProcessError):
  572. return default
  573. if not output:
  574. return default
  575. # With the C locale, the output should be mostly ASCII-compatible.
  576. # Decode from Latin-1 to prevent Unicode decode error.
  577. return output.decode('latin-1')
  578. ### Information about the used architecture
  579. # Default values for architecture; non-empty strings override the
  580. # defaults given as parameters
  581. _default_architecture = {
  582. 'win32': ('', 'WindowsPE'),
  583. 'win16': ('', 'Windows'),
  584. 'dos': ('', 'MSDOS'),
  585. }
  586. def architecture(executable=sys.executable, bits='', linkage=''):
  587. """ Queries the given executable (defaults to the Python interpreter
  588. binary) for various architecture information.
  589. Returns a tuple (bits, linkage) which contains information about
  590. the bit architecture and the linkage format used for the
  591. executable. Both values are returned as strings.
  592. Values that cannot be determined are returned as given by the
  593. parameter presets. If bits is given as '', the sizeof(pointer)
  594. (or sizeof(long) on Python version < 1.5.2) is used as
  595. indicator for the supported pointer size.
  596. The function relies on the system's "file" command to do the
  597. actual work. This is available on most if not all Unix
  598. platforms. On some non-Unix platforms where the "file" command
  599. does not exist and the executable is set to the Python interpreter
  600. binary defaults from _default_architecture are used.
  601. """
  602. # Use the sizeof(pointer) as default number of bits if nothing
  603. # else is given as default.
  604. if not bits:
  605. import struct
  606. size = struct.calcsize('P')
  607. bits = str(size * 8) + 'bit'
  608. # Get data from the 'file' system command
  609. if executable:
  610. fileout = _syscmd_file(executable, '')
  611. else:
  612. fileout = ''
  613. if not fileout and \
  614. executable == sys.executable:
  615. # "file" command did not return anything; we'll try to provide
  616. # some sensible defaults then...
  617. if sys.platform in _default_architecture:
  618. b, l = _default_architecture[sys.platform]
  619. if b:
  620. bits = b
  621. if l:
  622. linkage = l
  623. return bits, linkage
  624. if 'executable' not in fileout and 'shared object' not in fileout:
  625. # Format not supported
  626. return bits, linkage
  627. # Bits
  628. if '32-bit' in fileout:
  629. bits = '32bit'
  630. elif '64-bit' in fileout:
  631. bits = '64bit'
  632. # Linkage
  633. if 'ELF' in fileout:
  634. linkage = 'ELF'
  635. elif 'PE' in fileout:
  636. # E.g. Windows uses this format
  637. if 'Windows' in fileout:
  638. linkage = 'WindowsPE'
  639. else:
  640. linkage = 'PE'
  641. elif 'COFF' in fileout:
  642. linkage = 'COFF'
  643. elif 'MS-DOS' in fileout:
  644. linkage = 'MSDOS'
  645. else:
  646. # XXX the A.OUT format also falls under this class...
  647. pass
  648. return bits, linkage
  649. def _get_machine_win32():
  650. # Try to use the PROCESSOR_* environment variables
  651. # available on Win XP and later; see
  652. # http://support.microsoft.com/kb/888731 and
  653. # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
  654. # WOW64 processes mask the native architecture
  655. try:
  656. [arch, *_] = _wmi_query('CPU', 'Architecture')
  657. except OSError:
  658. pass
  659. else:
  660. try:
  661. arch = ['x86', 'MIPS', 'Alpha', 'PowerPC', None,
  662. 'ARM', 'ia64', None, None,
  663. 'AMD64', None, None, 'ARM64',
  664. ][int(arch)]
  665. except (ValueError, IndexError):
  666. pass
  667. else:
  668. if arch:
  669. return arch
  670. return (
  671. os.environ.get('PROCESSOR_ARCHITEW6432', '') or
  672. os.environ.get('PROCESSOR_ARCHITECTURE', '')
  673. )
  674. class _Processor:
  675. @classmethod
  676. def get(cls):
  677. func = getattr(cls, f'get_{sys.platform}', cls.from_subprocess)
  678. return func() or ''
  679. def get_win32():
  680. try:
  681. manufacturer, caption = _wmi_query('CPU', 'Manufacturer', 'Caption')
  682. except OSError:
  683. return os.environ.get('PROCESSOR_IDENTIFIER', _get_machine_win32())
  684. else:
  685. return f'{caption}, {manufacturer}'
  686. def get_OpenVMS():
  687. try:
  688. import vms_lib
  689. except ImportError:
  690. pass
  691. else:
  692. csid, cpu_number = vms_lib.getsyi('SYI$_CPU', 0)
  693. return 'Alpha' if cpu_number >= 128 else 'VAX'
  694. def from_subprocess():
  695. """
  696. Fall back to `uname -p`
  697. """
  698. try:
  699. import subprocess
  700. except ImportError:
  701. return None
  702. try:
  703. return subprocess.check_output(
  704. ['uname', '-p'],
  705. stderr=subprocess.DEVNULL,
  706. text=True,
  707. encoding="utf8",
  708. ).strip()
  709. except (OSError, subprocess.CalledProcessError):
  710. pass
  711. def _unknown_as_blank(val):
  712. return '' if val == 'unknown' else val
  713. ### Portable uname() interface
  714. class uname_result(
  715. collections.namedtuple(
  716. "uname_result_base",
  717. "system node release version machine")
  718. ):
  719. """
  720. A uname_result that's largely compatible with a
  721. simple namedtuple except that 'processor' is
  722. resolved late and cached to avoid calling "uname"
  723. except when needed.
  724. """
  725. _fields = ('system', 'node', 'release', 'version', 'machine', 'processor')
  726. @functools.cached_property
  727. def processor(self):
  728. return _unknown_as_blank(_Processor.get())
  729. def __iter__(self):
  730. return itertools.chain(
  731. super().__iter__(),
  732. (self.processor,)
  733. )
  734. @classmethod
  735. def _make(cls, iterable):
  736. # override factory to affect length check
  737. num_fields = len(cls._fields) - 1
  738. result = cls.__new__(cls, *iterable)
  739. if len(result) != num_fields + 1:
  740. msg = f'Expected {num_fields} arguments, got {len(result)}'
  741. raise TypeError(msg)
  742. return result
  743. def __getitem__(self, key):
  744. return tuple(self)[key]
  745. def __len__(self):
  746. return len(tuple(iter(self)))
  747. def __reduce__(self):
  748. return uname_result, tuple(self)[:len(self._fields) - 1]
  749. _uname_cache = None
  750. def uname():
  751. """ Fairly portable uname interface. Returns a tuple
  752. of strings (system, node, release, version, machine, processor)
  753. identifying the underlying platform.
  754. Note that unlike the os.uname function this also returns
  755. possible processor information as an additional tuple entry.
  756. Entries which cannot be determined are set to ''.
  757. """
  758. global _uname_cache
  759. if _uname_cache is not None:
  760. return _uname_cache
  761. # Get some infos from the builtin os.uname API...
  762. try:
  763. system, node, release, version, machine = infos = os.uname()
  764. except AttributeError:
  765. system = sys.platform
  766. node = _node()
  767. release = version = machine = ''
  768. infos = ()
  769. if not any(infos):
  770. # uname is not available
  771. # Try win32_ver() on win32 platforms
  772. if system == 'win32':
  773. release, version, csd, ptype = win32_ver()
  774. machine = machine or _get_machine_win32()
  775. # Try the 'ver' system command available on some
  776. # platforms
  777. if not (release and version):
  778. system, release, version = _syscmd_ver(system)
  779. # Normalize system to what win32_ver() normally returns
  780. # (_syscmd_ver() tends to return the vendor name as well)
  781. if system == 'Microsoft Windows':
  782. system = 'Windows'
  783. elif system == 'Microsoft' and release == 'Windows':
  784. # Under Windows Vista and Windows Server 2008,
  785. # Microsoft changed the output of the ver command. The
  786. # release is no longer printed. This causes the
  787. # system and release to be misidentified.
  788. system = 'Windows'
  789. if '6.0' == version[:3]:
  790. release = 'Vista'
  791. else:
  792. release = ''
  793. # In case we still don't know anything useful, we'll try to
  794. # help ourselves
  795. if system in ('win32', 'win16'):
  796. if not version:
  797. if system == 'win32':
  798. version = '32bit'
  799. else:
  800. version = '16bit'
  801. system = 'Windows'
  802. elif system[:4] == 'java':
  803. release, vendor, vminfo, osinfo = java_ver()
  804. system = 'Java'
  805. version = ', '.join(vminfo)
  806. if not version:
  807. version = vendor
  808. # System specific extensions
  809. if system == 'OpenVMS':
  810. # OpenVMS seems to have release and version mixed up
  811. if not release or release == '0':
  812. release = version
  813. version = ''
  814. # normalize name
  815. if system == 'Microsoft' and release == 'Windows':
  816. system = 'Windows'
  817. release = 'Vista'
  818. vals = system, node, release, version, machine
  819. # Replace 'unknown' values with the more portable ''
  820. _uname_cache = uname_result(*map(_unknown_as_blank, vals))
  821. return _uname_cache
  822. ### Direct interfaces to some of the uname() return values
  823. def system():
  824. """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  825. An empty string is returned if the value cannot be determined.
  826. """
  827. return uname().system
  828. def node():
  829. """ Returns the computer's network name (which may not be fully
  830. qualified)
  831. An empty string is returned if the value cannot be determined.
  832. """
  833. return uname().node
  834. def release():
  835. """ Returns the system's release, e.g. '2.2.0' or 'NT'
  836. An empty string is returned if the value cannot be determined.
  837. """
  838. return uname().release
  839. def version():
  840. """ Returns the system's release version, e.g. '#3 on degas'
  841. An empty string is returned if the value cannot be determined.
  842. """
  843. return uname().version
  844. def machine():
  845. """ Returns the machine type, e.g. 'i386'
  846. An empty string is returned if the value cannot be determined.
  847. """
  848. return uname().machine
  849. def processor():
  850. """ Returns the (true) processor name, e.g. 'amdk6'
  851. An empty string is returned if the value cannot be
  852. determined. Note that many platforms do not provide this
  853. information or simply return the same value as for machine(),
  854. e.g. NetBSD does this.
  855. """
  856. return uname().processor
  857. ### Various APIs for extracting information from sys.version
  858. _sys_version_cache = {}
  859. def _sys_version(sys_version=None):
  860. """ Returns a parsed version of Python's sys.version as tuple
  861. (name, version, branch, revision, buildno, builddate, compiler)
  862. referring to the Python implementation name, version, branch,
  863. revision, build number, build date/time as string and the compiler
  864. identification string.
  865. Note that unlike the Python sys.version, the returned value
  866. for the Python version will always include the patchlevel (it
  867. defaults to '.0').
  868. The function returns empty strings for tuple entries that
  869. cannot be determined.
  870. sys_version may be given to parse an alternative version
  871. string, e.g. if the version was read from a different Python
  872. interpreter.
  873. """
  874. # Get the Python version
  875. if sys_version is None:
  876. sys_version = sys.version
  877. # Try the cache first
  878. result = _sys_version_cache.get(sys_version, None)
  879. if result is not None:
  880. return result
  881. sys_version_parser = re.compile(
  882. r'([\w.+]+)\s*' # "version<space>"
  883. r'\(#?([^,]+)' # "(#buildno"
  884. r'(?:,\s*([\w ]*)' # ", builddate"
  885. r'(?:,\s*([\w :]*))?)?\)\s*' # ", buildtime)<space>"
  886. r'\[([^\]]+)\]?', re.ASCII) # "[compiler]"
  887. if sys.platform.startswith('java'):
  888. # Jython
  889. name = 'Jython'
  890. match = sys_version_parser.match(sys_version)
  891. if match is None:
  892. raise ValueError(
  893. 'failed to parse Jython sys.version: %s' %
  894. repr(sys_version))
  895. version, buildno, builddate, buildtime, _ = match.groups()
  896. if builddate is None:
  897. builddate = ''
  898. compiler = sys.platform
  899. elif "PyPy" in sys_version:
  900. # PyPy
  901. pypy_sys_version_parser = re.compile(
  902. r'([\w.+]+)\s*'
  903. r'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  904. r'\[PyPy [^\]]+\]?')
  905. name = "PyPy"
  906. match = pypy_sys_version_parser.match(sys_version)
  907. if match is None:
  908. raise ValueError("failed to parse PyPy sys.version: %s" %
  909. repr(sys_version))
  910. version, buildno, builddate, buildtime = match.groups()
  911. compiler = ""
  912. else:
  913. # CPython
  914. match = sys_version_parser.match(sys_version)
  915. if match is None:
  916. raise ValueError(
  917. 'failed to parse CPython sys.version: %s' %
  918. repr(sys_version))
  919. version, buildno, builddate, buildtime, compiler = \
  920. match.groups()
  921. name = 'CPython'
  922. if builddate is None:
  923. builddate = ''
  924. elif buildtime:
  925. builddate = builddate + ' ' + buildtime
  926. if hasattr(sys, '_git'):
  927. _, branch, revision = sys._git
  928. elif hasattr(sys, '_mercurial'):
  929. _, branch, revision = sys._mercurial
  930. else:
  931. branch = ''
  932. revision = ''
  933. # Add the patchlevel version if missing
  934. l = version.split('.')
  935. if len(l) == 2:
  936. l.append('0')
  937. version = '.'.join(l)
  938. # Build and cache the result
  939. result = (name, version, branch, revision, buildno, builddate, compiler)
  940. _sys_version_cache[sys_version] = result
  941. return result
  942. def python_implementation():
  943. """ Returns a string identifying the Python implementation.
  944. Currently, the following implementations are identified:
  945. 'CPython' (C implementation of Python),
  946. 'Jython' (Java implementation of Python),
  947. 'PyPy' (Python implementation of Python).
  948. """
  949. return _sys_version()[0]
  950. def python_version():
  951. """ Returns the Python version as string 'major.minor.patchlevel'
  952. Note that unlike the Python sys.version, the returned value
  953. will always include the patchlevel (it defaults to 0).
  954. """
  955. return _sys_version()[1]
  956. def python_version_tuple():
  957. """ Returns the Python version as tuple (major, minor, patchlevel)
  958. of strings.
  959. Note that unlike the Python sys.version, the returned value
  960. will always include the patchlevel (it defaults to 0).
  961. """
  962. return tuple(_sys_version()[1].split('.'))
  963. def python_branch():
  964. """ Returns a string identifying the Python implementation
  965. branch.
  966. For CPython this is the SCM branch from which the
  967. Python binary was built.
  968. If not available, an empty string is returned.
  969. """
  970. return _sys_version()[2]
  971. def python_revision():
  972. """ Returns a string identifying the Python implementation
  973. revision.
  974. For CPython this is the SCM revision from which the
  975. Python binary was built.
  976. If not available, an empty string is returned.
  977. """
  978. return _sys_version()[3]
  979. def python_build():
  980. """ Returns a tuple (buildno, builddate) stating the Python
  981. build number and date as strings.
  982. """
  983. return _sys_version()[4:6]
  984. def python_compiler():
  985. """ Returns a string identifying the compiler used for compiling
  986. Python.
  987. """
  988. return _sys_version()[6]
  989. ### The Opus Magnum of platform strings :-)
  990. _platform_cache = {}
  991. def platform(aliased=False, terse=False):
  992. """ Returns a single string identifying the underlying platform
  993. with as much useful information as possible (but no more :).
  994. The output is intended to be human readable rather than
  995. machine parseable. It may look different on different
  996. platforms and this is intended.
  997. If "aliased" is true, the function will use aliases for
  998. various platforms that report system names which differ from
  999. their common names, e.g. SunOS will be reported as
  1000. Solaris. The system_alias() function is used to implement
  1001. this.
  1002. Setting terse to true causes the function to return only the
  1003. absolute minimum information needed to identify the platform.
  1004. """
  1005. result = _platform_cache.get((aliased, terse), None)
  1006. if result is not None:
  1007. return result
  1008. # Get uname information and then apply platform specific cosmetics
  1009. # to it...
  1010. system, node, release, version, machine, processor = uname()
  1011. if machine == processor:
  1012. processor = ''
  1013. if aliased:
  1014. system, release, version = system_alias(system, release, version)
  1015. if system == 'Darwin':
  1016. # macOS (darwin kernel)
  1017. macos_release = mac_ver()[0]
  1018. if macos_release:
  1019. system = 'macOS'
  1020. release = macos_release
  1021. if system == 'Windows':
  1022. # MS platforms
  1023. rel, vers, csd, ptype = win32_ver(version)
  1024. if terse:
  1025. platform = _platform(system, release)
  1026. else:
  1027. platform = _platform(system, release, version, csd)
  1028. elif system == 'Linux':
  1029. # check for libc vs. glibc
  1030. libcname, libcversion = libc_ver()
  1031. platform = _platform(system, release, machine, processor,
  1032. 'with',
  1033. libcname+libcversion)
  1034. elif system == 'Java':
  1035. # Java platforms
  1036. r, v, vminfo, (os_name, os_version, os_arch) = java_ver()
  1037. if terse or not os_name:
  1038. platform = _platform(system, release, version)
  1039. else:
  1040. platform = _platform(system, release, version,
  1041. 'on',
  1042. os_name, os_version, os_arch)
  1043. else:
  1044. # Generic handler
  1045. if terse:
  1046. platform = _platform(system, release)
  1047. else:
  1048. bits, linkage = architecture(sys.executable)
  1049. platform = _platform(system, release, machine,
  1050. processor, bits, linkage)
  1051. _platform_cache[(aliased, terse)] = platform
  1052. return platform
  1053. ### freedesktop.org os-release standard
  1054. # https://www.freedesktop.org/software/systemd/man/os-release.html
  1055. # /etc takes precedence over /usr/lib
  1056. _os_release_candidates = ("/etc/os-release", "/usr/lib/os-release")
  1057. _os_release_cache = None
  1058. def _parse_os_release(lines):
  1059. # These fields are mandatory fields with well-known defaults
  1060. # in practice all Linux distributions override NAME, ID, and PRETTY_NAME.
  1061. info = {
  1062. "NAME": "Linux",
  1063. "ID": "linux",
  1064. "PRETTY_NAME": "Linux",
  1065. }
  1066. # NAME=value with optional quotes (' or "). The regular expression is less
  1067. # strict than shell lexer, but that's ok.
  1068. os_release_line = re.compile(
  1069. "^(?P<name>[a-zA-Z0-9_]+)=(?P<quote>[\"\']?)(?P<value>.*)(?P=quote)$"
  1070. )
  1071. # unescape five special characters mentioned in the standard
  1072. os_release_unescape = re.compile(r"\\([\\\$\"\'`])")
  1073. for line in lines:
  1074. mo = os_release_line.match(line)
  1075. if mo is not None:
  1076. info[mo.group('name')] = os_release_unescape.sub(
  1077. r"\1", mo.group('value')
  1078. )
  1079. return info
  1080. def freedesktop_os_release():
  1081. """Return operation system identification from freedesktop.org os-release
  1082. """
  1083. global _os_release_cache
  1084. if _os_release_cache is None:
  1085. errno = None
  1086. for candidate in _os_release_candidates:
  1087. try:
  1088. with open(candidate, encoding="utf-8") as f:
  1089. _os_release_cache = _parse_os_release(f)
  1090. break
  1091. except OSError as e:
  1092. errno = e.errno
  1093. else:
  1094. raise OSError(
  1095. errno,
  1096. f"Unable to read files {', '.join(_os_release_candidates)}"
  1097. )
  1098. return _os_release_cache.copy()
  1099. ### Command line interface
  1100. if __name__ == '__main__':
  1101. # Default is to print the aliased verbose platform string
  1102. terse = ('terse' in sys.argv or '--terse' in sys.argv)
  1103. aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
  1104. print(platform(aliased, terse))
  1105. sys.exit(0)