Linux发行版名称解析
我选择了这种方式来获取Linux发行版的名称:
ls /etc/*release
现在我需要从中提取出名称:
/etc/<name>-release
def checkDistro():
p = Popen('ls /etc/*release' , shell = True, stdout = PIPE)
distroRelease = p.stdout.read()
distroName = re.search( ur"\/etc\/(.*)\-release", distroRelease).group()
print distroName
但是这样打印出来的字符串和distroRelease里面的内容是一样的。
5 个回答
3
不建议解析ls
的输出。可以考虑使用glob()函数:
#!/usr/bin/env python
import os
import glob
def check_distro():
print os.path.basename(glob.glob('/etc/*-release')[0]).replace('-release', '')
if __name__ == '__main__':
check_distro()
7
另一种方法是使用内置的 platform.linux_distribution()
方法(在Python 2.6及以上版本中可用):
>>> import platform
>>> platform.linux_distribution()
('Red Hat Enterprise Linux Server', '5.1', 'Tikanga')
在旧版本的Python中,可以使用 platform.dist()
:
>>> import platform
>>> platform.dist()
('redhat', '5.1', 'Tikanga')
5
你需要使用 .group(1)
,因为你想要的是第一个捕获组的内容。如果不加参数,它默认会返回 .group(0)
,也就是整个匹配到的文本。