python错误代码处理

2024-04-19 01:54:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查安装了什么发行版:

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运行这个代码,就会出现错误代码,“done”不会打印(脚本结束得太早)。 如何解决这个问题?你知道吗


Tags: falsetruegetiflinuxdefcheckapt
2条回答

使用try/except。使用此方法,只需try运行apt。如果这不起作用(即except),请尝试运行rpm。如果这两个都不起作用,那么我建议使用Bereal建议的默认值platform.linux_distribution。 但是,由于很可能至少安装了其中一个,因此我认为最好使用try方法。此外,以后还可以包括yum等包。 try/except(常规)的示例代码:

try:
    x = input("Please input a number.\n")
except ValueError: # Someone put in a character
    print 'Not a valid number.\n'

在您的场景中:

import os
package_manager = ""
def check_linux():
    try:
        os.system("apt")
        package_manager = "apt"
    except:
        os.system("rpm")
        package_manager = "rpm"
    except: # WARNING! NEVER USE EXCEPT WITHOUT AN ERROR EXCEPT IN THE SIMPLEST OF SCENARIOS. When I find the correct error for this situation I will edit my code.
        os.sytem("yum")# ...etc, etc.
        package_manager = "yum"
    print package_manager

check_linux()
print 'done'

快乐的编码!祝你好运!你知道吗

subprocess.call如果找不到要运行的可执行文件,则会引发异常,Fedora和apt-get就是这种情况。您可以遍历PATH或尝试任何其他常见技巧,但幸运的是Python的标准库中已经有了函数platform.linux_distribution(),例如:

>>> import platform
>>> platform.linux_distribution()
('CentOS Linux', '7.0.1406', 'Core')

您可以检查它是如何实现的here。你知道吗

相关问题 更多 >