platform.py 42 KB

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