2015-04-15 52 views
4

沒有sys.getlinuxversion(),我覺得我可能必須從幾個地方拼湊它(這很好);但是,也許不是?什麼是sys.getwindowsversion()的linux等效

import sys, os 
from collections import namedtuple 

## This defines an interface similar to the object that getwindowsversion() returns 
## (I say 'similar' so I don't have to explain the descriptor magic behind it) 
WindowsVersion = namedtuple('WindowsVersion', 'major minor build platform product_type service_pack service_pack_major service_pack_minor suite_mask') 

## Looking for something that quacks like this: 
LinuxVersion = namedtuple('LinuxVersion', 'major minor build whatever attrs are needed') 

## To create something that quacks similarly to this (in case you're wondering) 
PlatformVersion = namedtuple('PlatformVersion', 'major minor micro build info') 

## EDIT: A newer version of Version, perhaps? 
class Version: 
    _fields = None 
    def __init__(self, *subversions, **info) 
     self.version = '.'.join([str(sub) for sub in subversions]) 
     self.info = info 
     instance_fields = self.__class__._fields 
     if instance_fields is not None: 
      if isinstance(instance_fields, str): 
       instance_fields = instance_fields.split() 
      for field in instance_fields: 
       if field in self.info: 
        setattr(self, field, self.info.pop(field)) 

## This makes the PlatformVersion (or any other Version) definition a mere: 
class PlatformVersion(Version): 
    _fields = 'build' ## :) 

## Now PlatformInfo looks something like: 
class PlatformInfo: 
    def __init__(self, *version_number, platform=None, version_info=None, **info): 
     self.platform = sys.platform if platform is None else platform 
     self.info = info 
     if self.platform in ('win32', 'win64'): 
      works_great = sys.getwindowsversion() 
      self.version = PlatformVersion(works_great.major, works_great.minor, works_great.service_pack_major, build=works_great.build, **dict(version_info)) 
     else: 
      self.version = your_answer(PlatformVersion(os.uname().release, build=os.uname().version, **dict(version_info))), 'hopefully' 
      self.version = self.version[0] ## lol 

謝謝!

回答

6

Linux(和所有的類Unix系統)具有uname系統調用提供這樣的信息:

>>> import os 
>>> os.uname().release 
'3.11.10-17-desktop' 

它顯示內核的版本。

需要注意的是Python的2它將返回元組,而不是namedtuple的:

>>> import os 
>>> os.uname()[2] 
'3.11.10-17-desktop' 
+0

呵呵,爽!畢竟,我不必拼湊在一起!謝謝! – Inversus

+2

或['platform.uname()'](https://docs.python.org/3/library/platform.html#platform.uname)爲跨平臺版本 – mata

相關問題