platform.py 39 KB

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