platform.py 42 KB

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