platform.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. #!/usr/bin/env python
  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. # Note: Please keep this module compatible to Python 1.5.2.
  13. #
  14. # Still needed:
  15. # * more support for WinCE
  16. # * support for MS-DOS (PythonDX ?)
  17. # * support for Amiga and other still unsupported platforms running Python
  18. # * support for additional Linux distributions
  19. #
  20. # Many thanks to all those who helped adding platform-specific
  21. # checks (in no particular order):
  22. #
  23. # Charles G Waldman, David Arnold, Gordon McMillan, Ben Darnell,
  24. # Jeff Bauer, Cliff Crawford, Ivan Van Laningham, Josef
  25. # Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
  26. # Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
  27. # Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
  28. # Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter, Steve
  29. # Dower
  30. #
  31. # History:
  32. #
  33. # <see CVS and SVN checkin messages for history>
  34. #
  35. # 1.0.8 - changed Windows support to read version from kernel32.dll
  36. # 1.0.7 - added DEV_NULL
  37. # 1.0.6 - added linux_distribution()
  38. # 1.0.5 - fixed Java support to allow running the module on Jython
  39. # 1.0.4 - added IronPython support
  40. # 1.0.3 - added normalization of Windows system name
  41. # 1.0.2 - added more Windows support
  42. # 1.0.1 - reformatted to make doc.py happy
  43. # 1.0.0 - reformatted a bit and checked into Python CVS
  44. # 0.8.0 - added sys.version parser and various new access
  45. # APIs (python_version(), python_compiler(), etc.)
  46. # 0.7.2 - fixed architecture() to use sizeof(pointer) where available
  47. # 0.7.1 - added support for Caldera OpenLinux
  48. # 0.7.0 - some fixes for WinCE; untabified the source file
  49. # 0.6.2 - support for OpenVMS - requires version 1.5.2-V006 or higher and
  50. # vms_lib.getsyi() configured
  51. # 0.6.1 - added code to prevent 'uname -p' on platforms which are
  52. # known not to support it
  53. # 0.6.0 - fixed win32_ver() to hopefully work on Win95,98,NT and Win2k;
  54. # did some cleanup of the interfaces - some APIs have changed
  55. # 0.5.5 - fixed another type in the MacOS code... should have
  56. # used more coffee today ;-)
  57. # 0.5.4 - fixed a few typos in the MacOS code
  58. # 0.5.3 - added experimental MacOS support; added better popen()
  59. # workarounds in _syscmd_ver() -- still not 100% elegant
  60. # though
  61. # 0.5.2 - fixed uname() to return '' instead of 'unknown' in all
  62. # return values (the system uname command tends to return
  63. # 'unknown' instead of just leaving the field emtpy)
  64. # 0.5.1 - included code for slackware dist; added exception handlers
  65. # to cover up situations where platforms don't have os.popen
  66. # (e.g. Mac) or fail on socket.gethostname(); fixed libc
  67. # detection RE
  68. # 0.5.0 - changed the API names referring to system commands to *syscmd*;
  69. # added java_ver(); made syscmd_ver() a private
  70. # API (was system_ver() in previous versions) -- use uname()
  71. # instead; extended the win32_ver() to also return processor
  72. # type information
  73. # 0.4.0 - added win32_ver() and modified the platform() output for WinXX
  74. # 0.3.4 - fixed a bug in _follow_symlinks()
  75. # 0.3.3 - fixed popen() and "file" command invokation bugs
  76. # 0.3.2 - added architecture() API and support for it in platform()
  77. # 0.3.1 - fixed syscmd_ver() RE to support Windows NT
  78. # 0.3.0 - added system alias support
  79. # 0.2.3 - removed 'wince' again... oh well.
  80. # 0.2.2 - added 'wince' to syscmd_ver() supported platforms
  81. # 0.2.1 - added cache logic and changed the platform string format
  82. # 0.2.0 - changed the API to use functions instead of module globals
  83. # since some action take too long to be run on module import
  84. # 0.1.0 - first release
  85. #
  86. # You can always get the latest version of this module at:
  87. #
  88. # http://www.egenix.com/files/python/platform.py
  89. #
  90. # If that URL should fail, try contacting the author.
  91. __copyright__ = """
  92. Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
  93. Copyright (c) 2000-2010, eGenix.com Software GmbH; mailto:info@egenix.com
  94. Permission to use, copy, modify, and distribute this software and its
  95. documentation for any purpose and without fee or royalty is hereby granted,
  96. provided that the above copyright notice appear in all copies and that
  97. both that copyright notice and this permission notice appear in
  98. supporting documentation or portions thereof, including modifications,
  99. that you make.
  100. EGENIX.COM SOFTWARE GMBH DISCLAIMS ALL WARRANTIES WITH REGARD TO
  101. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  102. FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
  103. INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  104. FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  105. NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  106. WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
  107. """
  108. __version__ = '1.0.7'
  109. import sys,string,os,re
  110. ### Globals & Constants
  111. # Determine the platform's /dev/null device
  112. try:
  113. DEV_NULL = os.devnull
  114. except AttributeError:
  115. # os.devnull was added in Python 2.4, so emulate it for earlier
  116. # Python versions
  117. if sys.platform in ('dos','win32','win16','os2'):
  118. # Use the old CP/M NUL as device name
  119. DEV_NULL = 'NUL'
  120. else:
  121. # Standard Unix uses /dev/null
  122. DEV_NULL = '/dev/null'
  123. ### Platform specific APIs
  124. _libc_search = re.compile(r'(__libc_init)'
  125. '|'
  126. '(GLIBC_([0-9.]+))'
  127. '|'
  128. '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)')
  129. def libc_ver(executable=sys.executable,lib='',version='',
  130. chunksize=2048):
  131. """ Tries to determine the libc version that the file executable
  132. (which defaults to the Python interpreter) is linked against.
  133. Returns a tuple of strings (lib,version) which default to the
  134. given parameters in case the lookup fails.
  135. Note that the function has intimate knowledge of how different
  136. libc versions add symbols to the executable and thus is probably
  137. only useable for executables compiled using gcc.
  138. The file is read and scanned in chunks of chunksize bytes.
  139. """
  140. if hasattr(os.path, 'realpath'):
  141. # Python 2.2 introduced os.path.realpath(); it is used
  142. # here to work around problems with Cygwin not being
  143. # able to open symlinks for reading
  144. executable = os.path.realpath(executable)
  145. f = open(executable,'rb')
  146. binary = f.read(chunksize)
  147. pos = 0
  148. while 1:
  149. m = _libc_search.search(binary,pos)
  150. if not m:
  151. binary = f.read(chunksize)
  152. if not binary:
  153. break
  154. pos = 0
  155. continue
  156. libcinit,glibc,glibcversion,so,threads,soversion = m.groups()
  157. if libcinit and not lib:
  158. lib = 'libc'
  159. elif glibc:
  160. if lib != 'glibc':
  161. lib = 'glibc'
  162. version = glibcversion
  163. elif glibcversion > version:
  164. version = glibcversion
  165. elif so:
  166. if lib != 'glibc':
  167. lib = 'libc'
  168. if soversion and soversion > version:
  169. version = soversion
  170. if threads and version[-len(threads):] != threads:
  171. version = version + threads
  172. pos = m.end()
  173. f.close()
  174. return lib,version
  175. def _dist_try_harder(distname,version,id):
  176. """ Tries some special tricks to get the distribution
  177. information in case the default method fails.
  178. Currently supports older SuSE Linux, Caldera OpenLinux and
  179. Slackware Linux distributions.
  180. """
  181. if os.path.exists('/var/adm/inst-log/info'):
  182. # SuSE Linux stores distribution information in that file
  183. info = open('/var/adm/inst-log/info').readlines()
  184. distname = 'SuSE'
  185. for line in info:
  186. tv = string.split(line)
  187. if len(tv) == 2:
  188. tag,value = tv
  189. else:
  190. continue
  191. if tag == 'MIN_DIST_VERSION':
  192. version = string.strip(value)
  193. elif tag == 'DIST_IDENT':
  194. values = string.split(value,'-')
  195. id = values[2]
  196. return distname,version,id
  197. if os.path.exists('/etc/.installed'):
  198. # Caldera OpenLinux has some infos in that file (thanks to Colin Kong)
  199. info = open('/etc/.installed').readlines()
  200. for line in info:
  201. pkg = string.split(line,'-')
  202. if len(pkg) >= 2 and pkg[0] == 'OpenLinux':
  203. # XXX does Caldera support non Intel platforms ? If yes,
  204. # where can we find the needed id ?
  205. return 'OpenLinux',pkg[1],id
  206. if os.path.isdir('/usr/lib/setup'):
  207. # Check for slackware version tag file (thanks to Greg Andruk)
  208. verfiles = os.listdir('/usr/lib/setup')
  209. for n in range(len(verfiles)-1, -1, -1):
  210. if verfiles[n][:14] != 'slack-version-':
  211. del verfiles[n]
  212. if verfiles:
  213. verfiles.sort()
  214. distname = 'slackware'
  215. version = verfiles[-1][14:]
  216. return distname,version,id
  217. return distname,version,id
  218. _release_filename = re.compile(r'(\w+)[-_](release|version)')
  219. _lsb_release_version = re.compile(r'(.+)'
  220. ' release '
  221. '([\d.]+)'
  222. '[^(]*(?:\((.+)\))?')
  223. _release_version = re.compile(r'([^0-9]+)'
  224. '(?: release )?'
  225. '([\d.]+)'
  226. '[^(]*(?:\((.+)\))?')
  227. # See also http://www.novell.com/coolsolutions/feature/11251.html
  228. # and http://linuxmafia.com/faq/Admin/release-files.html
  229. # and http://data.linux-ntfs.org/rpm/whichrpm
  230. # and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
  231. _supported_dists = (
  232. 'SuSE', 'debian', 'fedora', 'redhat', 'centos',
  233. 'mandrake', 'mandriva', 'rocks', 'slackware', 'yellowdog', 'gentoo',
  234. 'UnitedLinux', 'turbolinux')
  235. def _parse_release_file(firstline):
  236. # Default to empty 'version' and 'id' strings. Both defaults are used
  237. # when 'firstline' is empty. 'id' defaults to empty when an id can not
  238. # be deduced.
  239. version = ''
  240. id = ''
  241. # Parse the first line
  242. m = _lsb_release_version.match(firstline)
  243. if m is not None:
  244. # LSB format: "distro release x.x (codename)"
  245. return tuple(m.groups())
  246. # Pre-LSB format: "distro x.x (codename)"
  247. m = _release_version.match(firstline)
  248. if m is not None:
  249. return tuple(m.groups())
  250. # Unknown format... take the first two words
  251. l = string.split(string.strip(firstline))
  252. if l:
  253. version = l[0]
  254. if len(l) > 1:
  255. id = l[1]
  256. return '', version, id
  257. def linux_distribution(distname='', version='', id='',
  258. supported_dists=_supported_dists,
  259. full_distribution_name=1):
  260. """ Tries to determine the name of the Linux OS distribution name.
  261. The function first looks for a distribution release file in
  262. /etc and then reverts to _dist_try_harder() in case no
  263. suitable files are found.
  264. supported_dists may be given to define the set of Linux
  265. distributions to look for. It defaults to a list of currently
  266. supported Linux distributions identified by their release file
  267. name.
  268. If full_distribution_name is true (default), the full
  269. distribution read from the OS is returned. Otherwise the short
  270. name taken from supported_dists is used.
  271. Returns a tuple (distname,version,id) which default to the
  272. args given as parameters.
  273. """
  274. try:
  275. etc = os.listdir('/etc')
  276. except os.error:
  277. # Probably not a Unix system
  278. return distname,version,id
  279. etc.sort()
  280. for file in etc:
  281. m = _release_filename.match(file)
  282. if m is not None:
  283. _distname,dummy = m.groups()
  284. if _distname in supported_dists:
  285. distname = _distname
  286. break
  287. else:
  288. return _dist_try_harder(distname,version,id)
  289. # Read the first line
  290. f = open('/etc/'+file, 'r')
  291. firstline = f.readline()
  292. f.close()
  293. _distname, _version, _id = _parse_release_file(firstline)
  294. if _distname and full_distribution_name:
  295. distname = _distname
  296. if _version:
  297. version = _version
  298. if _id:
  299. id = _id
  300. return distname, version, id
  301. # To maintain backwards compatibility:
  302. def dist(distname='',version='',id='',
  303. supported_dists=_supported_dists):
  304. """ Tries to determine the name of the Linux OS distribution name.
  305. The function first looks for a distribution release file in
  306. /etc and then reverts to _dist_try_harder() in case no
  307. suitable files are found.
  308. Returns a tuple (distname,version,id) which default to the
  309. args given as parameters.
  310. """
  311. return linux_distribution(distname, version, id,
  312. supported_dists=supported_dists,
  313. full_distribution_name=0)
  314. class _popen:
  315. """ Fairly portable (alternative) popen implementation.
  316. This is mostly needed in case os.popen() is not available, or
  317. doesn't work as advertised, e.g. in Win9X GUI programs like
  318. PythonWin or IDLE.
  319. Writing to the pipe is currently not supported.
  320. """
  321. tmpfile = ''
  322. pipe = None
  323. bufsize = None
  324. mode = 'r'
  325. def __init__(self,cmd,mode='r',bufsize=None):
  326. if mode != 'r':
  327. raise ValueError,'popen()-emulation only supports read mode'
  328. import tempfile
  329. self.tmpfile = tmpfile = tempfile.mktemp()
  330. os.system(cmd + ' > %s' % tmpfile)
  331. self.pipe = open(tmpfile,'rb')
  332. self.bufsize = bufsize
  333. self.mode = mode
  334. def read(self):
  335. return self.pipe.read()
  336. def readlines(self):
  337. if self.bufsize is not None:
  338. return self.pipe.readlines()
  339. def close(self,
  340. remove=os.unlink,error=os.error):
  341. if self.pipe:
  342. rc = self.pipe.close()
  343. else:
  344. rc = 255
  345. if self.tmpfile:
  346. try:
  347. remove(self.tmpfile)
  348. except error:
  349. pass
  350. return rc
  351. # Alias
  352. __del__ = close
  353. def popen(cmd, mode='r', bufsize=None):
  354. """ Portable popen() interface.
  355. """
  356. # Find a working popen implementation preferring win32pipe.popen
  357. # over os.popen over _popen
  358. popen = None
  359. if os.environ.get('OS','') == 'Windows_NT':
  360. # On NT win32pipe should work; on Win9x it hangs due to bugs
  361. # in the MS C lib (see MS KnowledgeBase article Q150956)
  362. try:
  363. import win32pipe
  364. except ImportError:
  365. pass
  366. else:
  367. popen = win32pipe.popen
  368. if popen is None:
  369. if hasattr(os,'popen'):
  370. popen = os.popen
  371. # Check whether it works... it doesn't in GUI programs
  372. # on Windows platforms
  373. if sys.platform == 'win32': # XXX Others too ?
  374. try:
  375. popen('')
  376. except os.error:
  377. popen = _popen
  378. else:
  379. popen = _popen
  380. if bufsize is None:
  381. return popen(cmd,mode)
  382. else:
  383. return popen(cmd,mode,bufsize)
  384. def _norm_version(version, build=''):
  385. """ Normalize the version and build strings and return a single
  386. version string using the format major.minor.build (or patchlevel).
  387. """
  388. l = string.split(version,'.')
  389. if build:
  390. l.append(build)
  391. try:
  392. ints = map(int,l)
  393. except ValueError:
  394. strings = l
  395. else:
  396. strings = map(str,ints)
  397. version = string.join(strings[:3],'.')
  398. return version
  399. _ver_output = re.compile(r'(?:([\w ]+) ([\w.]+) '
  400. '.*'
  401. '\[.* ([\d.]+)\])')
  402. # Examples of VER command output:
  403. #
  404. # Windows 2000: Microsoft Windows 2000 [Version 5.00.2195]
  405. # Windows XP: Microsoft Windows XP [Version 5.1.2600]
  406. # Windows Vista: Microsoft Windows [Version 6.0.6002]
  407. #
  408. # Note that the "Version" string gets localized on different
  409. # Windows versions.
  410. def _syscmd_ver(system='', release='', version='',
  411. supported_platforms=('win32','win16','dos','os2')):
  412. """ Tries to figure out the OS version used and returns
  413. a tuple (system,release,version).
  414. It uses the "ver" shell command for this which is known
  415. to exists on Windows, DOS and OS/2. XXX Others too ?
  416. In case this fails, the given parameters are used as
  417. defaults.
  418. """
  419. if sys.platform not in supported_platforms:
  420. return system,release,version
  421. # Try some common cmd strings
  422. for cmd in ('ver','command /c ver','cmd /c ver'):
  423. try:
  424. pipe = popen(cmd)
  425. info = pipe.read()
  426. if pipe.close():
  427. raise os.error,'command failed'
  428. # XXX How can I suppress shell errors from being written
  429. # to stderr ?
  430. except os.error,why:
  431. #print 'Command %s failed: %s' % (cmd,why)
  432. continue
  433. except IOError,why:
  434. #print 'Command %s failed: %s' % (cmd,why)
  435. continue
  436. else:
  437. break
  438. else:
  439. return system,release,version
  440. # Parse the output
  441. info = string.strip(info)
  442. m = _ver_output.match(info)
  443. if m is not None:
  444. system,release,version = m.groups()
  445. # Strip trailing dots from version and release
  446. if release[-1] == '.':
  447. release = release[:-1]
  448. if version[-1] == '.':
  449. version = version[:-1]
  450. # Normalize the version and build strings (eliminating additional
  451. # zeros)
  452. version = _norm_version(version)
  453. return system,release,version
  454. _WIN32_CLIENT_RELEASES = {
  455. (5, 0): "2000",
  456. (5, 1): "XP",
  457. # Strictly, 5.2 client is XP 64-bit, but platform.py historically
  458. # has always called it 2003 Server
  459. (5, 2): "2003Server",
  460. (5, None): "post2003",
  461. (6, 0): "Vista",
  462. (6, 1): "7",
  463. (6, 2): "8",
  464. (6, 3): "8.1",
  465. (6, None): "post8.1",
  466. (10, 0): "10",
  467. (10, None): "post10",
  468. }
  469. # Server release name lookup will default to client names if necessary
  470. _WIN32_SERVER_RELEASES = {
  471. (5, 2): "2003Server",
  472. (6, 0): "2008Server",
  473. (6, 1): "2008ServerR2",
  474. (6, 2): "2012Server",
  475. (6, 3): "2012ServerR2",
  476. (6, None): "post2012ServerR2",
  477. }
  478. def _get_real_winver(maj, min, build):
  479. if maj < 6 or (maj == 6 and min < 2):
  480. return maj, min, build
  481. from ctypes import (c_buffer, POINTER, byref, create_unicode_buffer,
  482. Structure, WinDLL)
  483. from ctypes.wintypes import DWORD, HANDLE
  484. class VS_FIXEDFILEINFO(Structure):
  485. _fields_ = [
  486. ("dwSignature", DWORD),
  487. ("dwStrucVersion", DWORD),
  488. ("dwFileVersionMS", DWORD),
  489. ("dwFileVersionLS", DWORD),
  490. ("dwProductVersionMS", DWORD),
  491. ("dwProductVersionLS", DWORD),
  492. ("dwFileFlagsMask", DWORD),
  493. ("dwFileFlags", DWORD),
  494. ("dwFileOS", DWORD),
  495. ("dwFileType", DWORD),
  496. ("dwFileSubtype", DWORD),
  497. ("dwFileDateMS", DWORD),
  498. ("dwFileDateLS", DWORD),
  499. ]
  500. kernel32 = WinDLL('kernel32')
  501. version = WinDLL('version')
  502. # We will immediately double the length up to MAX_PATH, but the
  503. # path may be longer, so we retry until the returned string is
  504. # shorter than our buffer.
  505. name_len = actual_len = 130
  506. while actual_len == name_len:
  507. name_len *= 2
  508. name = create_unicode_buffer(name_len)
  509. actual_len = kernel32.GetModuleFileNameW(HANDLE(kernel32._handle),
  510. name, len(name))
  511. if not actual_len:
  512. return maj, min, build
  513. size = version.GetFileVersionInfoSizeW(name, None)
  514. if not size:
  515. return maj, min, build
  516. ver_block = c_buffer(size)
  517. if (not version.GetFileVersionInfoW(name, None, size, ver_block) or
  518. not ver_block):
  519. return maj, min, build
  520. pvi = POINTER(VS_FIXEDFILEINFO)()
  521. if not version.VerQueryValueW(ver_block, "", byref(pvi), byref(DWORD())):
  522. return maj, min, build
  523. maj = pvi.contents.dwProductVersionMS >> 16
  524. min = pvi.contents.dwProductVersionMS & 0xFFFF
  525. build = pvi.contents.dwProductVersionLS >> 16
  526. return maj, min, build
  527. def win32_ver(release='', version='', csd='', ptype=''):
  528. try:
  529. from sys import getwindowsversion
  530. except ImportError:
  531. return release, version, csd, ptype
  532. try:
  533. from winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
  534. except ImportError:
  535. from _winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
  536. winver = getwindowsversion()
  537. maj, min, build = _get_real_winver(*winver[:3])
  538. version = '{0}.{1}.{2}'.format(maj, min, build)
  539. release = (_WIN32_CLIENT_RELEASES.get((maj, min)) or
  540. _WIN32_CLIENT_RELEASES.get((maj, None)) or
  541. release)
  542. # getwindowsversion() reflect the compatibility mode Python is
  543. # running under, and so the service pack value is only going to be
  544. # valid if the versions match.
  545. if winver[:2] == (maj, min):
  546. try:
  547. csd = 'SP{}'.format(winver.service_pack_major)
  548. except AttributeError:
  549. if csd[:13] == 'Service Pack ':
  550. csd = 'SP' + csd[13:]
  551. # VER_NT_SERVER = 3
  552. if getattr(winver, 'product', None) == 3:
  553. release = (_WIN32_SERVER_RELEASES.get((maj, min)) or
  554. _WIN32_SERVER_RELEASES.get((maj, None)) or
  555. release)
  556. key = None
  557. try:
  558. key = OpenKeyEx(HKEY_LOCAL_MACHINE,
  559. r'SOFTWARE\Microsoft\Windows NT\CurrentVersion')
  560. ptype = QueryValueEx(key, 'CurrentType')[0]
  561. except:
  562. pass
  563. finally:
  564. if key:
  565. CloseKey(key)
  566. return release, version, csd, ptype
  567. def _mac_ver_lookup(selectors,default=None):
  568. from gestalt import gestalt
  569. import MacOS
  570. l = []
  571. append = l.append
  572. for selector in selectors:
  573. try:
  574. append(gestalt(selector))
  575. except (RuntimeError, MacOS.Error):
  576. append(default)
  577. return l
  578. def _bcd2str(bcd):
  579. return hex(bcd)[2:]
  580. def _mac_ver_gestalt():
  581. """
  582. Thanks to Mark R. Levinson for mailing documentation links and
  583. code examples for this function. Documentation for the
  584. gestalt() API is available online at:
  585. http://www.rgaros.nl/gestalt/
  586. """
  587. # Check whether the version info module is available
  588. try:
  589. import gestalt
  590. import MacOS
  591. except ImportError:
  592. return None
  593. # Get the infos
  594. sysv,sysa = _mac_ver_lookup(('sysv','sysa'))
  595. # Decode the infos
  596. if sysv:
  597. major = (sysv & 0xFF00) >> 8
  598. minor = (sysv & 0x00F0) >> 4
  599. patch = (sysv & 0x000F)
  600. if (major, minor) >= (10, 4):
  601. # the 'sysv' gestald cannot return patchlevels
  602. # higher than 9. Apple introduced 3 new
  603. # gestalt codes in 10.4 to deal with this
  604. # issue (needed because patch levels can
  605. # run higher than 9, such as 10.4.11)
  606. major,minor,patch = _mac_ver_lookup(('sys1','sys2','sys3'))
  607. release = '%i.%i.%i' %(major, minor, patch)
  608. else:
  609. release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
  610. if sysa:
  611. machine = {0x1: '68k',
  612. 0x2: 'PowerPC',
  613. 0xa: 'i386'}.get(sysa,'')
  614. versioninfo=('', '', '')
  615. return release,versioninfo,machine
  616. def _mac_ver_xml():
  617. fn = '/System/Library/CoreServices/SystemVersion.plist'
  618. if not os.path.exists(fn):
  619. return None
  620. try:
  621. import plistlib
  622. except ImportError:
  623. return None
  624. pl = plistlib.readPlist(fn)
  625. release = pl['ProductVersion']
  626. versioninfo=('', '', '')
  627. machine = os.uname()[4]
  628. if machine in ('ppc', 'Power Macintosh'):
  629. # for compatibility with the gestalt based code
  630. machine = 'PowerPC'
  631. return release,versioninfo,machine
  632. def mac_ver(release='',versioninfo=('','',''),machine=''):
  633. """ Get MacOS version information and return it as tuple (release,
  634. versioninfo, machine) with versioninfo being a tuple (version,
  635. dev_stage, non_release_version).
  636. Entries which cannot be determined are set to the parameter values
  637. which default to ''. All tuple entries are strings.
  638. """
  639. # First try reading the information from an XML file which should
  640. # always be present
  641. info = _mac_ver_xml()
  642. if info is not None:
  643. return info
  644. # If that doesn't work for some reason fall back to reading the
  645. # information using gestalt calls.
  646. info = _mac_ver_gestalt()
  647. if info is not None:
  648. return info
  649. # If that also doesn't work return the default values
  650. return release,versioninfo,machine
  651. def _java_getprop(name,default):
  652. from java.lang import System
  653. try:
  654. value = System.getProperty(name)
  655. if value is None:
  656. return default
  657. return value
  658. except AttributeError:
  659. return default
  660. def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
  661. """ Version interface for Jython.
  662. Returns a tuple (release,vendor,vminfo,osinfo) with vminfo being
  663. a tuple (vm_name,vm_release,vm_vendor) and osinfo being a
  664. tuple (os_name,os_version,os_arch).
  665. Values which cannot be determined are set to the defaults
  666. given as parameters (which all default to '').
  667. """
  668. # Import the needed APIs
  669. try:
  670. import java.lang
  671. except ImportError:
  672. return release,vendor,vminfo,osinfo
  673. vendor = _java_getprop('java.vendor', vendor)
  674. release = _java_getprop('java.version', release)
  675. vm_name, vm_release, vm_vendor = vminfo
  676. vm_name = _java_getprop('java.vm.name', vm_name)
  677. vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
  678. vm_release = _java_getprop('java.vm.version', vm_release)
  679. vminfo = vm_name, vm_release, vm_vendor
  680. os_name, os_version, os_arch = osinfo
  681. os_arch = _java_getprop('java.os.arch', os_arch)
  682. os_name = _java_getprop('java.os.name', os_name)
  683. os_version = _java_getprop('java.os.version', os_version)
  684. osinfo = os_name, os_version, os_arch
  685. return release, vendor, vminfo, osinfo
  686. ### System name aliasing
  687. def system_alias(system,release,version):
  688. """ Returns (system,release,version) aliased to common
  689. marketing names used for some systems.
  690. It also does some reordering of the information in some cases
  691. where it would otherwise cause confusion.
  692. """
  693. if system == 'Rhapsody':
  694. # Apple's BSD derivative
  695. # XXX How can we determine the marketing release number ?
  696. return 'MacOS X Server',system+release,version
  697. elif system == 'SunOS':
  698. # Sun's OS
  699. if release < '5':
  700. # These releases use the old name SunOS
  701. return system,release,version
  702. # Modify release (marketing release = SunOS release - 3)
  703. l = string.split(release,'.')
  704. if l:
  705. try:
  706. major = int(l[0])
  707. except ValueError:
  708. pass
  709. else:
  710. major = major - 3
  711. l[0] = str(major)
  712. release = string.join(l,'.')
  713. if release < '6':
  714. system = 'Solaris'
  715. else:
  716. # XXX Whatever the new SunOS marketing name is...
  717. system = 'Solaris'
  718. elif system == 'IRIX64':
  719. # IRIX reports IRIX64 on platforms with 64-bit support; yet it
  720. # is really a version and not a different platform, since 32-bit
  721. # apps are also supported..
  722. system = 'IRIX'
  723. if version:
  724. version = version + ' (64bit)'
  725. else:
  726. version = '64bit'
  727. elif system in ('win32','win16'):
  728. # In case one of the other tricks
  729. system = 'Windows'
  730. return system,release,version
  731. ### Various internal helpers
  732. def _platform(*args):
  733. """ Helper to format the platform string in a filename
  734. compatible format e.g. "system-version-machine".
  735. """
  736. # Format the platform string
  737. platform = string.join(
  738. map(string.strip,
  739. filter(len, args)),
  740. '-')
  741. # Cleanup some possible filename obstacles...
  742. replace = string.replace
  743. platform = replace(platform,' ','_')
  744. platform = replace(platform,'/','-')
  745. platform = replace(platform,'\\','-')
  746. platform = replace(platform,':','-')
  747. platform = replace(platform,';','-')
  748. platform = replace(platform,'"','-')
  749. platform = replace(platform,'(','-')
  750. platform = replace(platform,')','-')
  751. # No need to report 'unknown' information...
  752. platform = replace(platform,'unknown','')
  753. # Fold '--'s and remove trailing '-'
  754. while 1:
  755. cleaned = replace(platform,'--','-')
  756. if cleaned == platform:
  757. break
  758. platform = cleaned
  759. while platform[-1] == '-':
  760. platform = platform[:-1]
  761. return platform
  762. def _node(default=''):
  763. """ Helper to determine the node name of this machine.
  764. """
  765. try:
  766. import socket
  767. except ImportError:
  768. # No sockets...
  769. return default
  770. try:
  771. return socket.gethostname()
  772. except socket.error:
  773. # Still not working...
  774. return default
  775. # os.path.abspath is new in Python 1.5.2:
  776. if not hasattr(os.path,'abspath'):
  777. def _abspath(path,
  778. isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
  779. normpath=os.path.normpath):
  780. if not isabs(path):
  781. path = join(getcwd(), path)
  782. return normpath(path)
  783. else:
  784. _abspath = os.path.abspath
  785. def _follow_symlinks(filepath):
  786. """ In case filepath is a symlink, follow it until a
  787. real file is reached.
  788. """
  789. filepath = _abspath(filepath)
  790. while os.path.islink(filepath):
  791. filepath = os.path.normpath(
  792. os.path.join(os.path.dirname(filepath),os.readlink(filepath)))
  793. return filepath
  794. def _syscmd_uname(option,default=''):
  795. """ Interface to the system's uname command.
  796. """
  797. if sys.platform in ('dos','win32','win16','os2'):
  798. # XXX Others too ?
  799. return default
  800. try:
  801. f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
  802. except (AttributeError,os.error):
  803. return default
  804. output = string.strip(f.read())
  805. rc = f.close()
  806. if not output or rc:
  807. return default
  808. else:
  809. return output
  810. def _syscmd_file(target,default=''):
  811. """ Interface to the system's file command.
  812. The function uses the -b option of the file command to have it
  813. ommit the filename in its output and if possible the -L option
  814. to have the command follow symlinks. It returns default in
  815. case the command should fail.
  816. """
  817. # We do the import here to avoid a bootstrap issue.
  818. # See c73b90b6dadd changeset.
  819. #
  820. # [..]
  821. # ranlib libpython2.7.a
  822. # gcc -o python \
  823. # Modules/python.o \
  824. # libpython2.7.a -lsocket -lnsl -ldl -lm
  825. # Traceback (most recent call last):
  826. # File "./setup.py", line 8, in <module>
  827. # from platform import machine as platform_machine
  828. # File "[..]/build/Lib/platform.py", line 116, in <module>
  829. # import sys,string,os,re,subprocess
  830. # File "[..]/build/Lib/subprocess.py", line 429, in <module>
  831. # import select
  832. # ImportError: No module named select
  833. import subprocess
  834. if sys.platform in ('dos','win32','win16','os2'):
  835. # XXX Others too ?
  836. return default
  837. target = _follow_symlinks(target)
  838. try:
  839. proc = subprocess.Popen(['file', target],
  840. stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  841. except (AttributeError,os.error):
  842. return default
  843. output = proc.communicate()[0]
  844. rc = proc.wait()
  845. if not output or rc:
  846. return default
  847. else:
  848. return output
  849. ### Information about the used architecture
  850. # Default values for architecture; non-empty strings override the
  851. # defaults given as parameters
  852. _default_architecture = {
  853. 'win32': ('','WindowsPE'),
  854. 'win16': ('','Windows'),
  855. 'dos': ('','MSDOS'),
  856. }
  857. _architecture_split = re.compile(r'[\s,]').split
  858. def architecture(executable=sys.executable,bits='',linkage=''):
  859. """ Queries the given executable (defaults to the Python interpreter
  860. binary) for various architecture information.
  861. Returns a tuple (bits,linkage) which contains information about
  862. the bit architecture and the linkage format used for the
  863. executable. Both values are returned as strings.
  864. Values that cannot be determined are returned as given by the
  865. parameter presets. If bits is given as '', the sizeof(pointer)
  866. (or sizeof(long) on Python version < 1.5.2) is used as
  867. indicator for the supported pointer size.
  868. The function relies on the system's "file" command to do the
  869. actual work. This is available on most if not all Unix
  870. platforms. On some non-Unix platforms where the "file" command
  871. does not exist and the executable is set to the Python interpreter
  872. binary defaults from _default_architecture are used.
  873. """
  874. # Use the sizeof(pointer) as default number of bits if nothing
  875. # else is given as default.
  876. if not bits:
  877. import struct
  878. try:
  879. size = struct.calcsize('P')
  880. except struct.error:
  881. # Older installations can only query longs
  882. size = struct.calcsize('l')
  883. bits = str(size*8) + 'bit'
  884. # Get data from the 'file' system command
  885. if executable:
  886. output = _syscmd_file(executable, '')
  887. else:
  888. output = ''
  889. if not output and \
  890. executable == sys.executable:
  891. # "file" command did not return anything; we'll try to provide
  892. # some sensible defaults then...
  893. if sys.platform in _default_architecture:
  894. b, l = _default_architecture[sys.platform]
  895. if b:
  896. bits = b
  897. if l:
  898. linkage = l
  899. return bits, linkage
  900. # Split the output into a list of strings omitting the filename
  901. fileout = _architecture_split(output)[1:]
  902. if 'executable' not in fileout:
  903. # Format not supported
  904. return bits,linkage
  905. # Bits
  906. if '32-bit' in fileout:
  907. bits = '32bit'
  908. elif 'N32' in fileout:
  909. # On Irix only
  910. bits = 'n32bit'
  911. elif '64-bit' in fileout:
  912. bits = '64bit'
  913. # Linkage
  914. if 'ELF' in fileout:
  915. linkage = 'ELF'
  916. elif 'PE' in fileout:
  917. # E.g. Windows uses this format
  918. if 'Windows' in fileout:
  919. linkage = 'WindowsPE'
  920. else:
  921. linkage = 'PE'
  922. elif 'COFF' in fileout:
  923. linkage = 'COFF'
  924. elif 'MS-DOS' in fileout:
  925. linkage = 'MSDOS'
  926. else:
  927. # XXX the A.OUT format also falls under this class...
  928. pass
  929. return bits,linkage
  930. ### Portable uname() interface
  931. _uname_cache = None
  932. def uname():
  933. """ Fairly portable uname interface. Returns a tuple
  934. of strings (system,node,release,version,machine,processor)
  935. identifying the underlying platform.
  936. Note that unlike the os.uname function this also returns
  937. possible processor information as an additional tuple entry.
  938. Entries which cannot be determined are set to ''.
  939. """
  940. global _uname_cache
  941. no_os_uname = 0
  942. if _uname_cache is not None:
  943. return _uname_cache
  944. processor = ''
  945. # Get some infos from the builtin os.uname API...
  946. try:
  947. system,node,release,version,machine = os.uname()
  948. except AttributeError:
  949. no_os_uname = 1
  950. if no_os_uname or not filter(None, (system, node, release, version, machine)):
  951. # Hmm, no there is either no uname or uname has returned
  952. #'unknowns'... we'll have to poke around the system then.
  953. if no_os_uname:
  954. system = sys.platform
  955. release = ''
  956. version = ''
  957. node = _node()
  958. machine = ''
  959. use_syscmd_ver = 1
  960. # Try win32_ver() on win32 platforms
  961. if system == 'win32':
  962. release,version,csd,ptype = win32_ver()
  963. if release and version:
  964. use_syscmd_ver = 0
  965. # Try to use the PROCESSOR_* environment variables
  966. # available on Win XP and later; see
  967. # http://support.microsoft.com/kb/888731 and
  968. # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
  969. if not machine:
  970. # WOW64 processes mask the native architecture
  971. if "PROCESSOR_ARCHITEW6432" in os.environ:
  972. machine = os.environ.get("PROCESSOR_ARCHITEW6432", '')
  973. else:
  974. machine = os.environ.get('PROCESSOR_ARCHITECTURE', '')
  975. if not processor:
  976. processor = os.environ.get('PROCESSOR_IDENTIFIER', machine)
  977. # Try the 'ver' system command available on some
  978. # platforms
  979. if use_syscmd_ver:
  980. system,release,version = _syscmd_ver(system)
  981. # Normalize system to what win32_ver() normally returns
  982. # (_syscmd_ver() tends to return the vendor name as well)
  983. if system == 'Microsoft Windows':
  984. system = 'Windows'
  985. elif system == 'Microsoft' and release == 'Windows':
  986. # Under Windows Vista and Windows Server 2008,
  987. # Microsoft changed the output of the ver command. The
  988. # release is no longer printed. This causes the
  989. # system and release to be misidentified.
  990. system = 'Windows'
  991. if '6.0' == version[:3]:
  992. release = 'Vista'
  993. else:
  994. release = ''
  995. # In case we still don't know anything useful, we'll try to
  996. # help ourselves
  997. if system in ('win32','win16'):
  998. if not version:
  999. if system == 'win32':
  1000. version = '32bit'
  1001. else:
  1002. version = '16bit'
  1003. system = 'Windows'
  1004. elif system[:4] == 'java':
  1005. release,vendor,vminfo,osinfo = java_ver()
  1006. system = 'Java'
  1007. version = string.join(vminfo,', ')
  1008. if not version:
  1009. version = vendor
  1010. # System specific extensions
  1011. if system == 'OpenVMS':
  1012. # OpenVMS seems to have release and version mixed up
  1013. if not release or release == '0':
  1014. release = version
  1015. version = ''
  1016. # Get processor information
  1017. try:
  1018. import vms_lib
  1019. except ImportError:
  1020. pass
  1021. else:
  1022. csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0)
  1023. if (cpu_number >= 128):
  1024. processor = 'Alpha'
  1025. else:
  1026. processor = 'VAX'
  1027. if not processor:
  1028. # Get processor information from the uname system command
  1029. processor = _syscmd_uname('-p','')
  1030. #If any unknowns still exist, replace them with ''s, which are more portable
  1031. if system == 'unknown':
  1032. system = ''
  1033. if node == 'unknown':
  1034. node = ''
  1035. if release == 'unknown':
  1036. release = ''
  1037. if version == 'unknown':
  1038. version = ''
  1039. if machine == 'unknown':
  1040. machine = ''
  1041. if processor == 'unknown':
  1042. processor = ''
  1043. # normalize name
  1044. if system == 'Microsoft' and release == 'Windows':
  1045. system = 'Windows'
  1046. release = 'Vista'
  1047. _uname_cache = system,node,release,version,machine,processor
  1048. return _uname_cache
  1049. ### Direct interfaces to some of the uname() return values
  1050. def system():
  1051. """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
  1052. An empty string is returned if the value cannot be determined.
  1053. """
  1054. return uname()[0]
  1055. def node():
  1056. """ Returns the computer's network name (which may not be fully
  1057. qualified)
  1058. An empty string is returned if the value cannot be determined.
  1059. """
  1060. return uname()[1]
  1061. def release():
  1062. """ Returns the system's release, e.g. '2.2.0' or 'NT'
  1063. An empty string is returned if the value cannot be determined.
  1064. """
  1065. return uname()[2]
  1066. def version():
  1067. """ Returns the system's release version, e.g. '#3 on degas'
  1068. An empty string is returned if the value cannot be determined.
  1069. """
  1070. return uname()[3]
  1071. def machine():
  1072. """ Returns the machine type, e.g. 'i386'
  1073. An empty string is returned if the value cannot be determined.
  1074. """
  1075. return uname()[4]
  1076. def processor():
  1077. """ Returns the (true) processor name, e.g. 'amdk6'
  1078. An empty string is returned if the value cannot be
  1079. determined. Note that many platforms do not provide this
  1080. information or simply return the same value as for machine(),
  1081. e.g. NetBSD does this.
  1082. """
  1083. return uname()[5]
  1084. ### Various APIs for extracting information from sys.version
  1085. _sys_version_parser = re.compile(
  1086. r'([\w.+]+)\s*' # "version<space>"
  1087. r'\(#?([^,]+)' # "(#buildno"
  1088. r'(?:,\s*([\w ]*)' # ", builddate"
  1089. r'(?:,\s*([\w :]*))?)?\)\s*' # ", buildtime)<space>"
  1090. r'\[([^\]]+)\]?') # "[compiler]"
  1091. _ironpython_sys_version_parser = re.compile(
  1092. r'IronPython\s*'
  1093. '([\d\.]+)'
  1094. '(?: \(([\d\.]+)\))?'
  1095. ' on (.NET [\d\.]+)')
  1096. # IronPython covering 2.6 and 2.7
  1097. _ironpython26_sys_version_parser = re.compile(
  1098. r'([\d.]+)\s*'
  1099. '\(IronPython\s*'
  1100. '[\d.]+\s*'
  1101. '\(([\d.]+)\) on ([\w.]+ [\d.]+(?: \(\d+-bit\))?)\)'
  1102. )
  1103. _pypy_sys_version_parser = re.compile(
  1104. r'([\w.+]+)\s*'
  1105. '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
  1106. '\[PyPy [^\]]+\]?')
  1107. _sys_version_cache = {}
  1108. def _sys_version(sys_version=None):
  1109. """ Returns a parsed version of Python's sys.version as tuple
  1110. (name, version, branch, revision, buildno, builddate, compiler)
  1111. referring to the Python implementation name, version, branch,
  1112. revision, build number, build date/time as string and the compiler
  1113. identification string.
  1114. Note that unlike the Python sys.version, the returned value
  1115. for the Python version will always include the patchlevel (it
  1116. defaults to '.0').
  1117. The function returns empty strings for tuple entries that
  1118. cannot be determined.
  1119. sys_version may be given to parse an alternative version
  1120. string, e.g. if the version was read from a different Python
  1121. interpreter.
  1122. """
  1123. # Get the Python version
  1124. if sys_version is None:
  1125. sys_version = sys.version
  1126. # Try the cache first
  1127. result = _sys_version_cache.get(sys_version, None)
  1128. if result is not None:
  1129. return result
  1130. # Parse it
  1131. if 'IronPython' in sys_version:
  1132. # IronPython
  1133. name = 'IronPython'
  1134. if sys_version.startswith('IronPython'):
  1135. match = _ironpython_sys_version_parser.match(sys_version)
  1136. else:
  1137. match = _ironpython26_sys_version_parser.match(sys_version)
  1138. if match is None:
  1139. raise ValueError(
  1140. 'failed to parse IronPython sys.version: %s' %
  1141. repr(sys_version))
  1142. version, alt_version, compiler = match.groups()
  1143. buildno = ''
  1144. builddate = ''
  1145. elif sys.platform.startswith('java'):
  1146. # Jython
  1147. name = 'Jython'
  1148. match = _sys_version_parser.match(sys_version)
  1149. if match is None:
  1150. raise ValueError(
  1151. 'failed to parse Jython sys.version: %s' %
  1152. repr(sys_version))
  1153. version, buildno, builddate, buildtime, _ = match.groups()
  1154. if builddate is None:
  1155. builddate = ''
  1156. compiler = sys.platform
  1157. elif "PyPy" in sys_version:
  1158. # PyPy
  1159. name = "PyPy"
  1160. match = _pypy_sys_version_parser.match(sys_version)
  1161. if match is None:
  1162. raise ValueError("failed to parse PyPy sys.version: %s" %
  1163. repr(sys_version))
  1164. version, buildno, builddate, buildtime = match.groups()
  1165. compiler = ""
  1166. else:
  1167. # CPython
  1168. match = _sys_version_parser.match(sys_version)
  1169. if match is None:
  1170. raise ValueError(
  1171. 'failed to parse CPython sys.version: %s' %
  1172. repr(sys_version))
  1173. version, buildno, builddate, buildtime, compiler = \
  1174. match.groups()
  1175. name = 'CPython'
  1176. if builddate is None:
  1177. builddate = ''
  1178. elif buildtime:
  1179. builddate = builddate + ' ' + buildtime
  1180. if hasattr(sys, 'subversion'):
  1181. # sys.subversion was added in Python 2.5
  1182. _, branch, revision = sys.subversion
  1183. else:
  1184. branch = ''
  1185. revision = ''
  1186. # Add the patchlevel version if missing
  1187. l = string.split(version, '.')
  1188. if len(l) == 2:
  1189. l.append('0')
  1190. version = string.join(l, '.')
  1191. # Build and cache the result
  1192. result = (name, version, branch, revision, buildno, builddate, compiler)
  1193. _sys_version_cache[sys_version] = result
  1194. return result
  1195. def python_implementation():
  1196. """ Returns a string identifying the Python implementation.
  1197. Currently, the following implementations are identified:
  1198. 'CPython' (C implementation of Python),
  1199. 'IronPython' (.NET implementation of Python),
  1200. 'Jython' (Java implementation of Python),
  1201. 'PyPy' (Python implementation of Python).
  1202. """
  1203. return _sys_version()[0]
  1204. def python_version():
  1205. """ Returns the Python version as string 'major.minor.patchlevel'
  1206. Note that unlike the Python sys.version, the returned value
  1207. will always include the patchlevel (it defaults to 0).
  1208. """
  1209. return _sys_version()[1]
  1210. def python_version_tuple():
  1211. """ Returns the Python version as tuple (major, minor, patchlevel)
  1212. of strings.
  1213. Note that unlike the Python sys.version, the returned value
  1214. will always include the patchlevel (it defaults to 0).
  1215. """
  1216. return tuple(string.split(_sys_version()[1], '.'))
  1217. def python_branch():
  1218. """ Returns a string identifying the Python implementation
  1219. branch.
  1220. For CPython this is the Subversion branch from which the
  1221. Python binary was built.
  1222. If not available, an empty string is returned.
  1223. """
  1224. return _sys_version()[2]
  1225. def python_revision():
  1226. """ Returns a string identifying the Python implementation
  1227. revision.
  1228. For CPython this is the Subversion revision from which the
  1229. Python binary was built.
  1230. If not available, an empty string is returned.
  1231. """
  1232. return _sys_version()[3]
  1233. def python_build():
  1234. """ Returns a tuple (buildno, builddate) stating the Python
  1235. build number and date as strings.
  1236. """
  1237. return _sys_version()[4:6]
  1238. def python_compiler():
  1239. """ Returns a string identifying the compiler used for compiling
  1240. Python.
  1241. """
  1242. return _sys_version()[6]
  1243. ### The Opus Magnum of platform strings :-)
  1244. _platform_cache = {}
  1245. def platform(aliased=0, terse=0):
  1246. """ Returns a single string identifying the underlying platform
  1247. with as much useful information as possible (but no more :).
  1248. The output is intended to be human readable rather than
  1249. machine parseable. It may look different on different
  1250. platforms and this is intended.
  1251. If "aliased" is true, the function will use aliases for
  1252. various platforms that report system names which differ from
  1253. their common names, e.g. SunOS will be reported as
  1254. Solaris. The system_alias() function is used to implement
  1255. this.
  1256. Setting terse to true causes the function to return only the
  1257. absolute minimum information needed to identify the platform.
  1258. """
  1259. result = _platform_cache.get((aliased, terse), None)
  1260. if result is not None:
  1261. return result
  1262. # Get uname information and then apply platform specific cosmetics
  1263. # to it...
  1264. system,node,release,version,machine,processor = uname()
  1265. if machine == processor:
  1266. processor = ''
  1267. if aliased:
  1268. system,release,version = system_alias(system,release,version)
  1269. if system == 'Windows':
  1270. # MS platforms
  1271. rel,vers,csd,ptype = win32_ver(version)
  1272. if terse:
  1273. platform = _platform(system,release)
  1274. else:
  1275. platform = _platform(system,release,version,csd)
  1276. elif system in ('Linux',):
  1277. # Linux based systems
  1278. distname,distversion,distid = dist('')
  1279. if distname and not terse:
  1280. platform = _platform(system,release,machine,processor,
  1281. 'with',
  1282. distname,distversion,distid)
  1283. else:
  1284. # If the distribution name is unknown check for libc vs. glibc
  1285. libcname,libcversion = libc_ver(sys.executable)
  1286. platform = _platform(system,release,machine,processor,
  1287. 'with',
  1288. libcname+libcversion)
  1289. elif system == 'Java':
  1290. # Java platforms
  1291. r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
  1292. if terse or not os_name:
  1293. platform = _platform(system,release,version)
  1294. else:
  1295. platform = _platform(system,release,version,
  1296. 'on',
  1297. os_name,os_version,os_arch)
  1298. elif system == 'MacOS':
  1299. # MacOS platforms
  1300. if terse:
  1301. platform = _platform(system,release)
  1302. else:
  1303. platform = _platform(system,release,machine)
  1304. else:
  1305. # Generic handler
  1306. if terse:
  1307. platform = _platform(system,release)
  1308. else:
  1309. bits,linkage = architecture(sys.executable)
  1310. platform = _platform(system,release,machine,processor,bits,linkage)
  1311. _platform_cache[(aliased, terse)] = platform
  1312. return platform
  1313. ### Command line interface
  1314. if __name__ == '__main__':
  1315. # Default is to print the aliased verbose platform string
  1316. terse = ('terse' in sys.argv or '--terse' in sys.argv)
  1317. aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
  1318. print platform(aliased,terse)
  1319. sys.exit(0)