如何检测 Ubuntu 版本



我目前正在编写一个Python应用程序,可以更改一些网络配置文件。该应用程序需要在 Ubuntu 10.04 到 13.10 上运行。问题是,NetworkManager在不同的版本上以不同的方式损坏(尽管他们似乎最终在13.04 +中修复了它),这会导致与我的应用程序不兼容。

我已经找出了每个版本的问题并为其开发了解决方法,我只是不确定检测用户正在运行哪个版本的 Ubuntu 的最佳方法是什么。

到目前为止,我想出的最佳解决方案是解析lsb_release -a的输出,但这似乎是一个相当脆弱的解决方案,并且可能会在 Ubuntu 衍生的发行版(如 Mint)中失败,甚至可能在某些"官方"变体(Kubuntu、Xubuntu 等)中失败。

有没有一种好方法来检测给定 Linux 发行版的基本发行版和版本,以便我可以将我的应用所做的选择基于该版本?

为了简化代码,你可以做的一件事是真正了解lsb_release是如何编写的。它实际上是用python编写的。

因此,我们可以将您的大部分代码简化为:

>>> import lsb_release
>>> lsb_release.get_lsb_information()
{'RELEASE': '10.04', 'CODENAME': 'lucid', 'ID': 'Ubuntu', 'DESCRIPTION': 'Ubuntu 10.04.4 LTS'}

这不一定有助于所有子 ubuntu 发行版,但我不知道有任何内置表可以为您做到这一点。

最好的选择是使用操作系统和平台库。

import os
import platform
print os.name #returns os name in simple form
platform.system() #returns the base system, in your case Linux
platform.release() #returns release version

平台库应该是更有用的。

编辑:Rob对这篇文章的评论也强调了更具体的platform.linux_distribution()认为我会在这里指出这一点。

你也可以

阅读:/etc/lsb-release或/etc/debian_version作为文本文件

我使用gentoo系统,对我来说:

# cat /etc/lsb-release 
DISTRIB_ID="Gentoo"
def getOsFullDesc():
    name = ''
    if isfile('/etc/lsb-release'):
        lines = open('/etc/lsb-release').read().split('n')
        for line in lines:
            if line.startswith('DISTRIB_DESCRIPTION='):
                name = line.split('=')[1]
                if name[0]=='"' and name[-1]=='"':
                    return name[1:-1]
    if isfile('/suse/etc/SuSE-release'):
        return open('/suse/etc/SuSE-release').read().split('n')[0]
    try:
        import platform
        return ' '.join(platform.dist()).strip().title()
        #return platform.platform().replace('-', ' ')
    except ImportError:
        pass
    if os.name=='posix':
        osType = os.getenv('OSTYPE')
        if osType!='':
            return osType
    ## sys.platform == 'linux2'
    return os.name

最新更新