Python进程错误管理。无法捕获非零退出状态。

2024-06-28 15:19:46 发布

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

我使用python中的subprocess模块,使用sakis3g将3G加密狗连接到3G网络

请参阅我使用的代码:

check_output(['sakis3g', '--sudo', 'connect', 'OTHER="USBMODEM"', 'USBMODEM="12d1:1001"', 'APN="internet"'])

有时,我的加密狗可能会弹出一个错误,性质如下:“此设备没有任何GSM功能…”

我完全可以接受,因为它需要的只是一个简单的重试,它通常会工作得很好。在

但是使用子进程时,我会遇到错误returned non-zero exit status,它会使我的软件完全崩溃。在

因为我只需要一次重试,所以我尝试用try: ... except: ...编写代码。 我试图捕捉的错误是subprocess.CalledProcessError,如果根据the documentation非零退出状态,check_output应该返回该错误。在

然而,这似乎没有解决问题,问题仍然存在:

^{pr2}$

因此,我试图以最广泛的方式捕捉异常,只需简单地使用except:,即使这样做了,错误仍然会出现并使软件崩溃。在

我不知道如何正确地捕捉这个错误,有人能告诉我这里到底发生了什么,因为在这一点上(对我来说)很难捕捉到由子进程引起的错误。在

请参阅此处我打算使用的完整函数:

def connect_3G():
    while True:
        check_output(['sakis3g', '--sudo', 'connect', 'OTHER="USBMODEM"', 'USBMODEM="12d1:1001"', 'APN="internet"'])
        try:
            return 'Connected to ip: {}'.format(json.loads(requests.get('http://httpbin.org/ip').content)['origin'])
        except subprocess.CalledProcessError:
            print 'Oops, problem connecting to 3G. Better retry fam.'

Tags: 代码output进程checkconnect错误sudo请参阅
2条回答

我认为您做的是正确的…但是请将引发异常的代码移到try块中!在

def connect_3G():
    while True:
        try:
            check_output(['sakis3g', ' sudo', 'connect', 'OTHER="USBMODEM"', 'USBMODEM="12d1:1001"', 'APN="internet"'])
            return 'Connected to ip: {}'.format(json.loads(requests.get('http://httpbin.org/ip').content)['origin'])
        except subprocess.CalledProcessError:
            print 'Oops, problem connecting to 3G. Better retry fam.'

另外,只要打印出错误,就可以帮助您调试代码:

def connect_3G():
    while True:
        try:
            check_output(['sakis3g', ' sudo', 'connect', 'OTHER="USBMODEM"', 'USBMODEM="12d1:1001"', 'APN="internet"'])
            return 'Connected to ip: {}'.format(json.loads(requests.get('http://httpbin.org/ip').content)['origin'])
        except subprocess.CalledProcessError as error:
            print 'Oops, problem connecting to 3G. Better retry fam.', error.message

相关问题 更多 >