我想检查安装了什么发行版:
def check_linux():
if subprocess.call(['apt-get', '-v']) == 0: #if true
print('apt')
else: #if false
print('rpm')
check_linux()
print('done')
当我在 debian 发行版中尝试这个时,一切正常,我得到: stdout 中的“apt”和“done”。但是,如果我在 fedora 上运行此代码,则会出现错误代码并且“完成”不会打印(脚本结束得太早)。 如何解决这个问题?
最佳答案
subprocess.call
如果找不到要运行的可执行文件,则会引发异常,Fedora 和 apt-get
就是这种情况。您可以遍历 PATH
或尝试任何其他常用技巧,但幸运的是 Python 已经具有函数 platform.linux_distribution()在其标准库中,例如:
>>> import platform
>>> platform.linux_distribution()
('CentOS Linux', '7.0.1406', 'Core')
您可以查看它是如何实现的 here .
关于python错误代码处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32189162/