platform.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430
  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 sys, os, re, subprocess
  108. import warnings
  109. ### Globals & Constants
  110. # Determine the platform's /dev/null device
  111. try:
  112. DEV_NULL = os.devnull
  113. except AttributeError:
  114. # os.devnull was added in Python 2.4, so emulate it for earlier
  115. # Python versions
  116. if sys.platform in ('dos', 'win32', 'win16'):
  117. # Use the old CP/M NUL as device name
  118. DEV_NULL = 'NUL'
  119. else:
  120. # Standard Unix uses /dev/null
  121. DEV_NULL = '/dev/null'
  122. # Directory to search for configuration information on Unix.
  123. # Constant used by test_platform to test linux_distribution().
  124. _UNIXCONFDIR = '/etc'
  125. # Helper for comparing two version number strings.
  126. # Based on the description of the PHP's version_compare():
  127. # http://php.net/manual/en/function.version-compare.php
  128. _ver_stages = {
  129. # any string not found in this dict, will get 0 assigned
  130. 'dev': 10,
  131. 'alpha': 20, 'a': 20,
  132. 'beta': 30, 'b': 30,
  133. 'c': 40,
  134. 'RC': 50, 'rc': 50,
  135. # number, will get 100 assigned
  136. 'pl': 200, 'p': 200,
  137. }
  138. _component_re = re.compile(r'([0-9]+|[._+-])')
  139. def _comparable_version(version):
  140. result = []
  141. for v in _component_re.split(version):
  142. if v not in '._+-':
  143. try:
  144. v = int(v, 10)
  145. t = 100
  146. except ValueError:
  147. t = _ver_stages.get(v, 0)
  148. result.extend((t, v))
  149. return result
  150. ### Platform specific APIs
  151. _libc_search = re.compile(b'(__libc_init)'
  152. b'|'
  153. b'(GLIBC_([0-9.]+))'
  154. b'|'
  155. br'(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)', re.ASCII)
  156. def libc_ver(executable=sys.executable, lib='', version='', chunksize=16384):
  157. """ Tries to determine the libc version that the file executable
  158. (which defaults to the Python interpreter) is linked against.
  159. Returns a tuple of strings (lib,version) which default to the
  160. given parameters in case the lookup fails.
  161. Note that the function has intimate knowledge of how different
  162. libc versions add symbols to the executable and thus is probably
  163. only useable for executables compiled using gcc.
  164. The file is read and scanned in chunks of chunksize bytes.
  165. """
  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 _dist_try_harder(distname, version, id):
  209. """ Tries some special tricks to get the distribution
  210. information in case the default method fails.
  211. Currently supports older SuSE Linux, Caldera OpenLinux and
  212. Slackware Linux distributions.
  213. """
  214. if os.path.exists('/var/adm/inst-log/info'):
  215. # SuSE Linux stores distribution information in that file
  216. distname = 'SuSE'
  217. with open('/var/adm/inst-log/info') as f:
  218. for line in f:
  219. tv = line.split()
  220. if len(tv) == 2:
  221. tag, value = tv
  222. else:
  223. continue
  224. if tag == 'MIN_DIST_VERSION':
  225. version = value.strip()
  226. elif tag == 'DIST_IDENT':
  227. values = value.split('-')
  228. id = values[2]
  229. return distname, version, id
  230. if os.path.exists('/etc/.installed'):
  231. # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
  232. with open('/etc/.installed') as f:
  233. for line in f:
  234. pkg = line.split('-')
  235. if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
  236. # XXX does Caldera support non Intel platforms ? If yes,
  237. # where can we find the needed id ?
  238. return 'OpenLinux', pkg[1], id
  239. if os.path.isdir('/usr/lib/setup'):
  240. # Check for slackware version tag file (thanks to Greg Andruk)
  241. verfiles = os.listdir('/usr/lib/setup')
  242. for n in range(len(verfiles)-1, -1, -1):
  243. if verfiles[n][:14] != 'slack-version-':
  244. del verfiles[n]
  245. if verfiles:
  246. verfiles.sort()
  247. distname = 'slackware'
  248. version = verfiles[-1][14:]
  249. return distname, version, id
  250. return distname, version, id
  251. _release_filename = re.compile(r'(\w+)[-_](release|version)', re.ASCII)
  252. _lsb_release_version = re.compile(r'(.+)'
  253. r' release '
  254. r'([\d.]+)'
  255. r'[^(]*(?:\((.+)\))?', re.ASCII)
  256. _release_version = re.compile(r'([^0-9]+)'
  257. r'(?: release )?'
  258. r'([\d.]+)'
  259. r'[^(]*(?:\((.+)\))?', re.ASCII)
  260. # See also http://www.novell.com/coolsolutions/feature/11251.html
  261. # and http://linuxmafia.com/faq/Admin/release-files.html
  262. # and http://data.linux-ntfs.org/rpm/whichrpm
  263. # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
  264. _supported_dists = (
  265. 'SuSE', 'debian', 'fedora', 'redhat', 'centos',
  266. 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
  267. 'UnitedLinux', 'turbolinux', 'arch', 'mageia')
  268. def _parse_release_file(firstline):
  269. # Default to empty 'version' and 'id' strings. Both defaults are used
  270. # when 'firstline' is empty. 'id' defaults to empty when an id can not
  271. # be deduced.
  272. version = ''
  273. id = ''
  274. # Parse the first line
  275. m = _lsb_release_version.match(firstline)
  276. if m is not None:
  277. # LSB format: "distro release x.x (codename)"
  278. return tuple(m.groups())
  279. # Pre-LSB format: "distro x.x (codename)"
  280. m = _release_version.match(firstline)
  281. if m is not None:
  282. return tuple(m.groups())
  283. # Unknown format... take the first two words
  284. l = firstline.strip().split()
  285. if l:
  286. version = l[0]
  287. if len(l) > 1:
  288. id = l[1]
  289. return '', version, id
  290. def linux_distribution(distname='', version='', id='',
  291. supported_dists=_supported_dists,
  292. full_distribution_name=1):
  293. import warnings
  294. warnings.warn("dist() and linux_distribution() functions are deprecated "
  295. "in Python 3.5", DeprecationWarning, stacklevel=2)
  296. return _linux_distribution(distname, version, id, supported_dists,
  297. full_distribution_name)
  298. def _linux_distribution(distname, version, id, supported_dists,
  299. full_distribution_name):
  300. """ Tries to determine the name of the Linux OS distribution name.
  301. The function first looks for a distribution release file in
  302. /etc and then reverts to _dist_try_harder() in case no
  303. suitable files are found.
  304. supported_dists may be given to define the set of Linux
  305. distributions to look for. It defaults to a list of currently
  306. supported Linux distributions identified by their release file
  307. name.
  308. If full_distribution_name is true (default), the full
  309. distribution read from the OS is returned. Otherwise the short
  310. name taken from supported_dists is used.
  311. Returns a tuple (distname, version, id) which default to the
  312. args given as parameters.
  313. """
  314. try:
  315. etc = os.listdir(_UNIXCONFDIR)
  316. except OSError:
  317. # Probably not a Unix system
  318. return distname, version, id
  319. etc.sort()
  320. for file in etc:
  321. m = _release_filename.match(file)
  322. if m is not None:
  323. _distname, dummy = m.groups()
  324. if _distname in supported_dists:
  325. distname = _distname
  326. break
  327. else:
  328. return _dist_try_harder(distname, version, id)
  329. # Read the first line
  330. with open(os.path.join(_UNIXCONFDIR, file), 'r',
  331. encoding='utf-8', errors='surrogateescape') as f:
  332. firstline = f.readline()
  333. _distname, _version, _id = _parse_release_file(firstline)
  334. if _distname and full_distribution_name:
  335. distname = _distname
  336. if _version:
  337. version = _version
  338. if _id:
  339. id = _id
  340. return distname, version, id
  341. # To maintain backwards compatibility:
  342. def dist(distname='', version='', id='',
  343. supported_dists=_supported_dists):
  344. """ Tries to determine the name of the Linux OS distribution name.
  345. The function first looks for a distribution release file in
  346. /etc and then reverts to _dist_try_harder() in case no
  347. suitable files are found.
  348. Returns a tuple (distname, version, id) which default to the
  349. args given as parameters.
  350. """
  351. import warnings
  352. warnings.warn("dist() and linux_distribution() functions are deprecated "
  353. "in Python 3.5", DeprecationWarning, stacklevel=2)
  354. return _linux_distribution(distname, version, id,
  355. supported_dists=supported_dists,
  356. full_distribution_name=0)
  357. def popen(cmd, mode='r', bufsize=-1):
  358. """ Portable popen() interface.
  359. """
  360. import warnings
  361. warnings.warn('use os.popen instead', DeprecationWarning, stacklevel=2)
  362. return os.popen(cmd, mode, bufsize)
  363. def _norm_version(version, build=''):
  364. """ Normalize the version and build strings and return a single
  365. version string using the format major.minor.build (or patchlevel).
  366. """
  367. l = version.split('.')
  368. if build:
  369. l.append(build)
  370. try:
  371. ints = map(int, l)
  372. except ValueError:
  373. strings = l
  374. else:
  375. strings = list(map(str, ints))
  376. version = '.'.join(strings[:3])
  377. return version
  378. _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
  379. r'.*'
  380. r'\[.* ([\d.]+)\])')
  381. # Examples of VER command output:
  382. #
  383. # Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
  384. # Windows XP: Microsoft Windows XP [Version 5.1.2600]
  385. # Windows Vista: Microsoft Windows [Version 6.0.6002]
  386. #
  387. # Note that the "Version" string gets localized on different
  388. # Windows versions.
  389. def _syscmd_ver(system='', release='', version='',
  390. supported_platforms=('win32', 'win16', 'dos')):
  391. """ Tries to figure out the OS version used and returns
  392. a tuple (system, release, version).
  393. It uses the "ver" shell command for this which is known
  394. to exists on Windows, DOS. XXX Others too ?
  395. In case this fails, the given parameters are used as
  396. defaults.
  397. """
  398. if sys.platform not in supported_platforms:
  399. return system, release, version
  400. # Try some common cmd strings
  401. for cmd in ('ver', 'command /c ver', 'cmd /c ver'):
  402. try:
  403. pipe = os.popen(cmd)
  404. info = pipe.read()
  405. if pipe.close():
  406. raise OSError('command failed')
  407. # XXX How can I suppress shell errors from being written
  408. # to stderr ?
  409. except OSError as why:
  410. #print 'Command %s failed: %s' % (cmd, why)
  411. continue
  412. else:
  413. break
  414. else:
  415. return system, release, version
  416. # Parse the output
  417. info = info.strip()
  418. m = _ver_output.match(info)
  419. if m is not None:
  420. system, release, version = m.groups()
  421. # Strip trailing dots from version and release
  422. if release[-1] == '.':
  423. release = release[:-1]
  424. if version[-1] == '.':
  425. version = version[:-1]
  426. # Normalize the version and build strings (eliminating additional
  427. # zeros)
  428. version = _norm_version(version)
  429. return system, release, version
  430. _WIN32_CLIENT_RELEASES = {
  431. (5, 0): "2000",
  432. (5, 1): "XP",
  433. # Strictly, 5.2 client is XP 64-bit, but platform.py historically
  434. # has always called it 2003 Server
  435. (5, 2): "2003Server",
  436. (5, None): "post2003",
  437. (6, 0): "Vista",
  438. (6, 1): "7",
  439. (6, 2): "8",
  440. (6, 3): "8.1",
  441. (6, None): "post8.1",
  442. (10, 0): "10",
  443. (10, None): "post10",
  444. }
  445. # Server release name lookup will default to client names if necessary
  446. _WIN32_SERVER_RELEASES = {
  447. (5, 2): "2003Server",
  448. (6, 0): "2008Server",
  449. (6, 1): "2008ServerR2",
  450. (6, 2): "2012Server",
  451. (6, 3): "2012ServerR2",
  452. (6, None): "post2012ServerR2",
  453. }
  454. def win32_ver(release='', version='', csd='', ptype=''):
  455. try:
  456. from sys import getwindowsversion
  457. except ImportError:
  458. return release, version, csd, ptype
  459. winver = getwindowsversion()
  460. maj, min, build = winver.platform_version or winver[:3]
  461. version = '{0}.{1}.{2}'.format(maj, min, build)
  462. release = (_WIN32_CLIENT_RELEASES.get((maj, min)) or
  463. _WIN32_CLIENT_RELEASES.get((maj, None)) or
  464. release)
  465. # getwindowsversion() reflect the compatibility mode Python is
  466. # running under, and so the service pack value is only going to be
  467. # valid if the versions match.
  468. if winver[:2] == (maj, min):
  469. try:
  470. csd = 'SP{}'.format(winver.service_pack_major)
  471. except AttributeError:
  472. if csd[:13] == 'Service Pack ':
  473. csd = 'SP' + csd[13:]
  474. # VER_NT_SERVER = 3
  475. if getattr(winver, 'product_type', None) == 3:
  476. release = (_WIN32_SERVER_RELEASES.get((maj, min)) or
  477. _WIN32_SERVER_RELEASES.get((maj, None)) or
  478. release)
  479. try:
  480. try:
  481. import winreg
  482. except ImportError:
  483. import _winreg as winreg
  484. except ImportError:
  485. pass
  486. else:
  487. try:
  488. cvkey = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion'
  489. with winreg.OpenKeyEx(HKEY_LOCAL_MACHINE, cvkey) as key:
  490. ptype = QueryValueEx(key, 'CurrentType')[0]
  491. except:
  492. pass
  493. return release, version, csd, ptype
  494. def _mac_ver_xml():
  495. fn = '/System/Library/CoreServices/SystemVersion.plist'
  496. if not os.path.exists(fn):
  497. return None
  498. try:
  499. import plistlib
  500. except ImportError:
  501. return None
  502. with open(fn, 'rb') as f:
  503. pl = plistlib.load(f)
  504. release = pl['ProductVersion']
  505. versioninfo = ('', '', '')
  506. machine = os.uname().machine
  507. if machine in ('ppc', 'Power Macintosh'):
  508. # Canonical name
  509. machine = 'PowerPC'
  510. return release, versioninfo, machine
  511. def mac_ver(release='', versioninfo=('', '', ''), machine=''):
  512. """ Get MacOS version information and return it as tuple (release,
  513. versioninfo, machine) with versioninfo being a tuple (version,
  514. dev_stage, non_release_version).
  515. Entries which cannot be determined are set to the parameter values
  516. which default to ''. All tuple entries are strings.
  517. """
  518. # First try reading the information from an XML file which should
  519. # always be present
  520. info = _mac_ver_xml()
  521. if info is not None:
  522. return info
  523. # If that also doesn't work return the default values
  524. return release, versioninfo, machine
  525. def _java_getprop(name, default):
  526. from java.lang import System
  527. try:
  528. value = System.getProperty(name)
  529. if value is None:
  530. return default
  531. return value
  532. except AttributeError:
  533. return default
  534. def java_ver(release='', vendor='', vminfo=('', '', ''), osinfo=('', '', '')):
  535. """ Version interface for Jython.
  536. Returns a tuple (release, vendor, vminfo, osinfo) with vminfo being
  537. a tuple (vm_name, vm_release, vm_vendor) and osinfo being a
  538. tuple (os_name, os_version, os_arch).
  539. Values which cannot be determined are set to the defaults
  540. given as parameters (which all default to '').
  541. """
  542. # Import the needed APIs
  543. try:
  544. import java.lang
  545. except ImportError:
  546. return release, vendor, vminfo, osinfo
  547. vendor = _java_getprop('java.vendor', vendor)
  548. release = _java_getprop('java.version', release)
  549. vm_name, vm_release, vm_vendor = vminfo
  550. vm_name = _java_getprop('java.vm.name', vm_name)
  551. vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  552. vm_release = _java_getprop('java.vm.version', vm_release)
  553. vminfo = vm_name, vm_release, vm_vendor
  554. os_name, os_version, os_arch = osinfo
  555. os_arch = _java_getprop('java.os.arch', os_arch)
  556. os_name = _java_getprop('java.os.name', os_name)
  557. os_version = _java_getprop('java.os.version', os_version)
  558. osinfo = os_name, os_version, os_arch
  559. return release, vendor, vminfo, osinfo
  560. ### System name aliasing
  561. def system_alias(system, release, version):
  562. """ Returns (system, release, version) aliased to common
  563. marketing names used for some systems.
  564. It also does some reordering of the information in some cases
  565. where it would otherwise cause confusion.
  566. """
  567. if system == 'Rhapsody':
  568. # Apple's BSD derivative
  569. # XXX How can we determine the marketing release number ?
  570. return 'MacOS X Server', system+release, version
  571. elif system == 'SunOS':
  572. # Sun's OS
  573. if release < '5':
  574. # These releases use the old name SunOS
  575. return system, release, version
  576. # Modify release (marketing release = SunOS release - 3)
  577. l = release.split('.')
  578. if l:
  579. try:
  580. major = int(l[0])
  581. except ValueError:
  582. pass
  583. else:
  584. major = major - 3
  585. l[0] = str(major)
  586. release = '.'.join(l)
  587. if release < '6':
  588. system = 'Solaris'
  589. else:
  590. # XXX Whatever the new SunOS marketing name is...
  591. system = 'Solaris'
  592. elif system == 'IRIX64':
  593. # IRIX reports IRIX64 on platforms with 64-bit support; yet it
  594. # is really a version and not a different platform, since 32-bit
  595. # apps are also supported..
  596. system = 'IRIX'
  597. if version:
  598. version = version + ' (64bit)'
  599. else:
  600. version = '64bit'
  601. elif system in ('win32', 'win16'):
  602. # In case one of the other tricks
  603. system = 'Windows'
  604. return system, release, version
  605. ### Various internal helpers
  606. def _platform(*args):
  607. """ Helper to format the platform string in a filename
  608. compatible format e.g. "system-version-machine".
  609. """
  610. # Format the platform string
  611. platform = '-'.join(x.strip() for x in filter(len, args))
  612. # Cleanup some possible filename obstacles...
  613. platform = platform.replace(' ', '_')
  614. platform = platform.replace('/', '-')
  615. platform = platform.replace('\\', '-')
  616. platform = platform.replace(':', '-')
  617. platform = platform.replace(';', '-')
  618. platform = platform.replace('"', '-')
  619. platform = platform.replace('(', '-')
  620. platform = platform.replace(')', '-')
  621. # No need to report 'unknown' information...
  622. platform = platform.replace('unknown', '')
  623. # Fold '--'s and remove trailing '-'
  624. while 1:
  625. cleaned = platform.replace('--', '-')
  626. if cleaned == platform:
  627. break
  628. platform = cleaned
  629. while platform[-1] == '-':
  630. platform = platform[:-1]
  631. return platform
  632. def _node(default=''):
  633. """ Helper to determine the node name of this machine.
  634. """
  635. try:
  636. import socket
  637. except ImportError:
  638. # No sockets...
  639. return default
  640. try:
  641. return socket.gethostname()
  642. except OSError:
  643. # Still not working...
  644. return default
  645. def _follow_symlinks(filepath):
  646. """ In case filepath is a symlink, follow it until a
  647. real file is reached.
  648. """
  649. filepath = os.path.abspath(filepath)
  650. while os.path.islink(filepath):
  651. filepath = os.path.normpath(
  652. os.path.join(os.path.dirname(filepath), os.readlink(filepath)))
  653. return filepath
  654. def _syscmd_uname(option, default=''):
  655. """ Interface to the system's uname command.
  656. """
  657. if sys.platform in ('dos', 'win32', 'win16'):
  658. # XXX Others too ?
  659. return default
  660. try:
  661. f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
  662. except (AttributeError, OSError):
  663. return default
  664. output = f.read().strip()
  665. rc = f.close()
  666. if not output or rc:
  667. return default
  668. else:
  669. return output
  670. def _syscmd_file(target, default=''):
  671. """ Interface to the system's file command.
  672. The function uses the -b option of the file command to have it
  673. omit the filename in its output. Follow the symlinks. It returns
  674. default in case the command should fail.
  675. """
  676. if sys.platform in ('dos', 'win32', 'win16'):
  677. # XXX Others too ?
  678. return default
  679. target = _follow_symlinks(target)
  680. try:
  681. proc = subprocess.Popen(['file', target],
  682. stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  683. except (AttributeError, OSError):
  684. return default
  685. output = proc.communicate()[0].decode('latin-1')
  686. rc = proc.wait()
  687. if not output or rc:
  688. return default
  689. else:
  690. return output
  691. ### Information about the used architecture
  692. # Default values for architecture; non-empty strings override the
  693. # defaults given as parameters
  694. _default_architecture = {
  695. 'win32': ('', 'WindowsPE'),
  696. 'win16': ('', 'Windows'),
  697. 'dos': ('', 'MSDOS'),
  698. }
  699. def architecture(executable=sys.executable, bits='', linkage=''):
  700. """ Queries the given executable (defaults to the Python interpreter
  701. binary) for various architecture information.
  702. Returns a tuple (bits, linkage) which contains information about
  703. the bit architecture and the linkage format used for the
  704. executable. Both values are returned as strings.
  705. Values that cannot be determined are returned as given by the
  706. parameter presets. If bits is given as '', the sizeof(pointer)
  707. (or sizeof(long) on Python version < 1.5.2) is used as
  708. indicator for the supported pointer size.
  709. The function relies on the system's "file" command to do the
  710. actual work. This is available on most if not all Unix
  711. platforms. On some non-Unix platforms where the "file" command
  712. does not exist and the executable is set to the Python interpreter
  713. binary defaults from _default_architecture are used.
  714. """
  715. # Use the sizeof(pointer) as default number of bits if nothing
  716. # else is given as default.
  717. if not bits:
  718. import struct
  719. try:
  720. size = struct.calcsize('P')
  721. except struct.error:
  722. # Older installations can only query longs
  723. size = struct.calcsize('l')
  724. bits = str(size*8) + 'bit'
  725. # Get data from the 'file' system command
  726. if executable:
  727. fileout = _syscmd_file(executable, '')
  728. else:
  729. fileout = ''
  730. if not fileout and \
  731. executable == sys.executable:
  732. # "file" command did not return anything; we'll try to provide
  733. # some sensible defaults then...
  734. if sys.platform in _default_architecture:
  735. b, l = _default_architecture[sys.platform]
  736. if b:
  737. bits = b
  738. if l:
  739. linkage = l
  740. return bits, linkage
  741. if 'executable' not in fileout:
  742. # Format not supported
  743. return bits, linkage
  744. # Bits
  745. if '32-bit' in fileout:
  746. bits = '32bit'
  747. elif 'N32' in fileout:
  748. # On Irix only
  749. bits = 'n32bit'
  750. elif '64-bit' in fileout:
  751. bits = '64bit'
  752. # Linkage
  753. if 'ELF' in fileout:
  754. linkage = 'ELF'
  755. elif 'PE' in fileout:
  756. # E.g. Windows uses this format
  757. if 'Windows' in fileout:
  758. linkage = 'WindowsPE'
  759. else:
  760. linkage = 'PE'
  761. elif 'COFF' in fileout:
  762. linkage = 'COFF'
  763. elif 'MS-DOS' in fileout:
  764. linkage = 'MSDOS'
  765. else:
  766. # XXX the A.OUT format also falls under this class...
  767. pass
  768. return bits, linkage
  769. ### Portable uname() interface
  770. uname_result = collections.namedtuple("uname_result",
  771. "system node release version machine processor")
  772. _uname_cache = None
  773. def uname():
  774. """ Fairly portable uname interface. Returns a tuple
  775. of strings (system, node, release, version, machine, processor)
  776. identifying the underlying platform.
  777. Note that unlike the os.uname function this also returns
  778. possible processor information as an additional tuple entry.
  779. Entries which cannot be determined are set to ''.
  780. """
  781. global _uname_cache
  782. no_os_uname = 0
  783. if _uname_cache is not None:
  784. return _uname_cache
  785. processor = ''
  786. # Get some infos from the builtin os.uname API...
  787. try:
  788. system, node, release, version, machine = os.uname()
  789. except AttributeError:
  790. no_os_uname = 1
  791. if no_os_uname or not list(filter(None, (system, node, release, version, machine))):
  792. # Hmm, no there is either no uname or uname has returned
  793. #'unknowns'... we'll have to poke around the system then.
  794. if no_os_uname:
  795. system = sys.platform
  796. release = ''
  797. version = ''
  798. node = _node()
  799. machine = ''
  800. use_syscmd_ver = 1
  801. # Try win32_ver() on win32 platforms
  802. if system == 'win32':
  803. release, version, csd, ptype = win32_ver()
  804. if release and version:
  805. use_syscmd_ver = 0
  806. # Try to use the PROCESSOR_* environment variables
  807. # available on Win XP and later; see
  808. # http://support.microsoft.com/kb/888731 and
  809. # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
  810. if not machine:
  811. # WOW64 processes mask the native architecture
  812. if "PROCESSOR_ARCHITEW6432" in os.environ:
  813. machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
  814. else:
  815. machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  816. if not processor:
  817. processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
  818. # Try the 'ver' system command available on some
  819. # platforms
  820. if use_syscmd_ver:
  821. system, release, version = _syscmd_ver(system)
  822. # Normalize system to what win32_ver() normally returns
  823. # (_syscmd_ver() tends to return the vendor name as well)
  824. if system == 'Microsoft Windows':
  825. system = 'Windows'
  826. elif system == 'Microsoft' and release == 'Windows':
  827. # Under Windows Vista and Windows Server 2008,
  828. # Microsoft changed the output of the ver command. The
  829. # release is no longer printed. This causes the
  830. # system and release to be misidentified.
  831. system = 'Windows'
  832. if '6.0' == version[:3]:
  833. release = 'Vista'
  834. else:
  835. release = ''
  836. # In case we still don't know anything useful, we'll try to
  837. # help ourselves
  838. if system in ('win32', 'win16'):
  839. if not version:
  840. if system == 'win32':
  841. version = '32bit'
  842. else:
  843. version = '16bit'
  844. system = 'Windows'
  845. elif system[:4] == 'java':
  846. release, vendor, vminfo, osinfo = java_ver()
  847. system = 'Java'
  848. version = ', '.join(vminfo)
  849. if not version:
  850. version = vendor
  851. # System specific extensions
  852. if system == 'OpenVMS':
  853. # OpenVMS seems to have release and version mixed up
  854. if not release or release == '0':
  855. release = version
  856. version = ''
  857. # Get processor information
  858. try:
  859. import vms_lib
  860. except ImportError:
  861. pass
  862. else:
  863. csid, cpu_number = vms_lib.getsyi('SYI$_CPU', 0)
  864. if (cpu_number >= 128):
  865. processor = 'Alpha'
  866. else:
  867. processor = 'VAX'
  868. if not processor:
  869. # Get processor information from the uname system command
  870. processor = _syscmd_uname('-p', '')
  871. #If any unknowns still exist, replace them with ''s, which are more portable
  872. if system == 'unknown':
  873. system = ''
  874. if node == 'unknown':
  875. node = ''
  876. if release == 'unknown':
  877. release = ''
  878. if version == 'unknown':
  879. version = ''
  880. if machine == 'unknown':
  881. machine = ''
  882. if processor == 'unknown':
  883. processor = ''
  884. # normalize name
  885. if system == 'Microsoft' and release == 'Windows':
  886. system = 'Windows'
  887. release = 'Vista'
  888. _uname_cache = uname_result(system, node, release, version,
  889. machine, processor)
  890. return _uname_cache
  891. ### Direct interfaces to some of the uname() return values
  892. def system():
  893. """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  894. An empty string is returned if the value cannot be determined.
  895. """
  896. return uname().system
  897. def node():
  898. """ Returns the computer's network name (which may not be fully
  899. qualified)
  900. An empty string is returned if the value cannot be determined.
  901. """
  902. return uname().node
  903. def release():
  904. """ Returns the system's release, e.g. '2.2.0' or 'NT'
  905. An empty string is returned if the value cannot be determined.
  906. """
  907. return uname().release
  908. def version():
  909. """ Returns the system's release version, e.g. '#3 on degas'
  910. An empty string is returned if the value cannot be determined.
  911. """
  912. return uname().version
  913. def machine():
  914. """ Returns the machine type, e.g. 'i386'
  915. An empty string is returned if the value cannot be determined.
  916. """
  917. return uname().machine
  918. def processor():
  919. """ Returns the (true) processor name, e.g. 'amdk6'
  920. An empty string is returned if the value cannot be
  921. determined. Note that many platforms do not provide this
  922. information or simply return the same value as for machine(),
  923. e.g. NetBSD does this.
  924. """
  925. return uname().processor
  926. ### Various APIs for extracting information from sys.version
  927. _sys_version_parser = re.compile(
  928. r'([\w.+]+)\s*' # "version<space>"
  929. r'\(#?([^,]+)' # "(#buildno"
  930. r'(?:,\s*([\w ]*)' # ", builddate"
  931. r'(?:,\s*([\w :]*))?)?\)\s*' # ", buildtime)<space>"
  932. r'\[([^\]]+)\]?', re.ASCII) # "[compiler]"
  933. _ironpython_sys_version_parser = re.compile(
  934. r'IronPython\s*'
  935. r'([\d\.]+)'
  936. r'(?: \(([\d\.]+)\))?'
  937. r' on (.NET [\d\.]+)', re.ASCII)
  938. # IronPython covering 2.6 and 2.7
  939. _ironpython26_sys_version_parser = re.compile(
  940. r'([\d.]+)\s*'
  941. r'\(IronPython\s*'
  942. r'[\d.]+\s*'
  943. r'\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'
  944. )
  945. _pypy_sys_version_parser = re.compile(
  946. r'([\w.+]+)\s*'
  947. r'\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  948. r'\[PyPy [^\]]+\]?')
  949. _sys_version_cache = {}
  950. def _sys_version(sys_version=None):
  951. """ Returns a parsed version of Python's sys.version as tuple
  952. (name, version, branch, revision, buildno, builddate, compiler)
  953. referring to the Python implementation name, version, branch,
  954. revision, build number, build date/time as string and the compiler
  955. identification string.
  956. Note that unlike the Python sys.version, the returned value
  957. for the Python version will always include the patchlevel (it
  958. defaults to '.0').
  959. The function returns empty strings for tuple entries that
  960. cannot be determined.
  961. sys_version may be given to parse an alternative version
  962. string, e.g. if the version was read from a different Python
  963. interpreter.
  964. """
  965. # Get the Python version
  966. if sys_version is None:
  967. sys_version = sys.version
  968. # Try the cache first
  969. result = _sys_version_cache.get(sys_version, None)
  970. if result is not None:
  971. return result
  972. # Parse it
  973. if 'IronPython' in sys_version:
  974. # IronPython
  975. name = 'IronPython'
  976. if sys_version.startswith('IronPython'):
  977. match = _ironpython_sys_version_parser.match(sys_version)
  978. else:
  979. match = _ironpython26_sys_version_parser.match(sys_version)
  980. if match is None:
  981. raise ValueError(
  982. 'failed to parse IronPython sys.version: %s' %
  983. repr(sys_version))
  984. version, alt_version, compiler = match.groups()
  985. buildno = ''
  986. builddate = ''
  987. elif sys.platform.startswith('java'):
  988. # Jython
  989. name = 'Jython'
  990. match = _sys_version_parser.match(sys_version)
  991. if match is None:
  992. raise ValueError(
  993. 'failed to parse Jython sys.version: %s' %
  994. repr(sys_version))
  995. version, buildno, builddate, buildtime, _ = match.groups()
  996. if builddate is None:
  997. builddate = ''
  998. compiler = sys.platform
  999. elif "PyPy" in sys_version:
  1000. # PyPy
  1001. name = "PyPy"
  1002. match = _pypy_sys_version_parser.match(sys_version)
  1003. if match is None:
  1004. raise ValueError("failed to parse PyPy sys.version: %s" %
  1005. repr(sys_version))
  1006. version, buildno, builddate, buildtime = match.groups()
  1007. compiler = ""
  1008. else:
  1009. # CPython
  1010. match = _sys_version_parser.match(sys_version)
  1011. if match is None:
  1012. raise ValueError(
  1013. 'failed to parse CPython sys.version: %s' %
  1014. repr(sys_version))
  1015. version, buildno, builddate, buildtime, compiler = \
  1016. match.groups()
  1017. name = 'CPython'
  1018. if builddate is None:
  1019. builddate = ''
  1020. elif buildtime:
  1021. builddate = builddate + ' ' + buildtime
  1022. if hasattr(sys, '_git'):
  1023. _, branch, revision = sys._git
  1024. elif hasattr(sys, '_mercurial'):
  1025. _, branch, revision = sys._mercurial
  1026. else:
  1027. branch = ''
  1028. revision = ''
  1029. # Add the patchlevel version if missing
  1030. l = version.split('.')
  1031. if len(l) == 2:
  1032. l.append('0')
  1033. version = '.'.join(l)
  1034. # Build and cache the result
  1035. result = (name, version, branch, revision, buildno, builddate, compiler)
  1036. _sys_version_cache[sys_version] = result
  1037. return result
  1038. def python_implementation():
  1039. """ Returns a string identifying the Python implementation.
  1040. Currently, the following implementations are identified:
  1041. 'CPython' (C implementation of Python),
  1042. 'IronPython' (.NET implementation of Python),
  1043. 'Jython' (Java implementation of Python),
  1044. 'PyPy' (Python implementation of Python).
  1045. """
  1046. return _sys_version()[0]
  1047. def python_version():
  1048. """ Returns the Python version as string 'major.minor.patchlevel'
  1049. Note that unlike the Python sys.version, the returned value
  1050. will always include the patchlevel (it defaults to 0).
  1051. """
  1052. return _sys_version()[1]
  1053. def python_version_tuple():
  1054. """ Returns the Python version as tuple (major, minor, patchlevel)
  1055. of strings.
  1056. Note that unlike the Python sys.version, the returned value
  1057. will always include the patchlevel (it defaults to 0).
  1058. """
  1059. return tuple(_sys_version()[1].split('.'))
  1060. def python_branch():
  1061. """ Returns a string identifying the Python implementation
  1062. branch.
  1063. For CPython this is the SCM branch from which the
  1064. Python binary was built.
  1065. If not available, an empty string is returned.
  1066. """
  1067. return _sys_version()[2]
  1068. def python_revision():
  1069. """ Returns a string identifying the Python implementation
  1070. revision.
  1071. For CPython this is the SCM revision from which the
  1072. Python binary was built.
  1073. If not available, an empty string is returned.
  1074. """
  1075. return _sys_version()[3]
  1076. def python_build():
  1077. """ Returns a tuple (buildno, builddate) stating the Python
  1078. build number and date as strings.
  1079. """
  1080. return _sys_version()[4:6]
  1081. def python_compiler():
  1082. """ Returns a string identifying the compiler used for compiling
  1083. Python.
  1084. """
  1085. return _sys_version()[6]
  1086. ### The Opus Magnum of platform strings :-)
  1087. _platform_cache = {}
  1088. def platform(aliased=0, terse=0):
  1089. """ Returns a single string identifying the underlying platform
  1090. with as much useful information as possible (but no more :).
  1091. The output is intended to be human readable rather than
  1092. machine parseable. It may look different on different
  1093. platforms and this is intended.
  1094. If "aliased" is true, the function will use aliases for
  1095. various platforms that report system names which differ from
  1096. their common names, e.g. SunOS will be reported as
  1097. Solaris. The system_alias() function is used to implement
  1098. this.
  1099. Setting terse to true causes the function to return only the
  1100. absolute minimum information needed to identify the platform.
  1101. """
  1102. result = _platform_cache.get((aliased, terse), None)
  1103. if result is not None:
  1104. return result
  1105. # Get uname information and then apply platform specific cosmetics
  1106. # to it...
  1107. system, node, release, version, machine, processor = uname()
  1108. if machine == processor:
  1109. processor = ''
  1110. if aliased:
  1111. system, release, version = system_alias(system, release, version)
  1112. if system == 'Windows':
  1113. # MS platforms
  1114. rel, vers, csd, ptype = win32_ver(version)
  1115. if terse:
  1116. platform = _platform(system, release)
  1117. else:
  1118. platform = _platform(system, release, version, csd)
  1119. elif system in ('Linux',):
  1120. # Linux based systems
  1121. with warnings.catch_warnings():
  1122. # see issue #1322 for more information
  1123. warnings.filterwarnings(
  1124. 'ignore',
  1125. r'dist\(\) and linux_distribution\(\) '
  1126. 'functions are deprecated .*',
  1127. DeprecationWarning,
  1128. )
  1129. distname, distversion, distid = dist('')
  1130. if distname and not terse:
  1131. platform = _platform(system, release, machine, processor,
  1132. 'with',
  1133. distname, distversion, distid)
  1134. else:
  1135. # If the distribution name is unknown check for libc vs. glibc
  1136. libcname, libcversion = libc_ver(sys.executable)
  1137. platform = _platform(system, release, machine, processor,
  1138. 'with',
  1139. libcname+libcversion)
  1140. elif system == 'Java':
  1141. # Java platforms
  1142. r, v, vminfo, (os_name, os_version, os_arch) = java_ver()
  1143. if terse or not os_name:
  1144. platform = _platform(system, release, version)
  1145. else:
  1146. platform = _platform(system, release, version,
  1147. 'on',
  1148. os_name, os_version, os_arch)
  1149. elif system == 'MacOS':
  1150. # MacOS platforms
  1151. if terse:
  1152. platform = _platform(system, release)
  1153. else:
  1154. platform = _platform(system, release, machine)
  1155. else:
  1156. # Generic handler
  1157. if terse:
  1158. platform = _platform(system, release)
  1159. else:
  1160. bits, linkage = architecture(sys.executable)
  1161. platform = _platform(system, release, machine,
  1162. processor, bits, linkage)
  1163. _platform_cache[(aliased, terse)] = platform
  1164. return platform
  1165. ### Command line interface
  1166. if __name__ == '__main__':
  1167. # Default is to print the aliased verbose platform string
  1168. terse = ('terse' in sys.argv or '--terse' in sys.argv)
  1169. aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
  1170. print(platform(aliased, terse))
  1171. sys.exit(0)