platform.py 40 KB

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