Python'subprocess'CallledProcessError:Command'[...]'返回非零退出状态1

时间:2015-10-05 06:08:10

标签: python subprocess stdout popen

执行以下脚本......

import socket                   
import sys                          

from collections import OrderedDict
from subprocess import check_output
from threading import Thread    

[...]

class IpCheck(Thread):  

    RECEIVED_PACKAGES_RE = re.compile(r'(\d+) received')

    def __init__(self, ip):                         
        Thread.__init__(self)
        self.ip = ip
        self.result = None

    def run(self):                          
        match = self.RECEIVED_PACKAGES_RE.search(
            check_output(['ping', '-q', '-c2', '-W1', self.ip])
        )

        successful_ping_count = int(match.group(1)) if match else 0

        if successful_ping_count == 0:
            self.result = 'no response'
        elif successful_ping_count == 1:
            self.result = 'alive, but 50% package loss'
        elif successful_ping_count == 2:
            self.result = check_snmp(self.ip)
        else:
            assert False

[...]

...导致错误:

  

CalledProcessError:命令'[ping',' - q',' - c2',' - W1','10 .81.3.80']'返回非零退出状态1

check_output中添加“stderr = STDOUT”没有产生任何有用的反馈。

如何获取有关错误的更多信息,以便我对其进行故障排除?

2 个答案:

答案 0 :(得分:10)

subprocess.check_output在非零退出代码上引发CalledProcessError,如果出现问题,ping会返回非零退出代码(例如,未知的域名,或网站已关闭,或网站由于某种原因导致ICMP被阻止,或者您的Internet连接已关闭。

如果要检查输出和退出代码,请使用subprocess.Popen

import subprocess
import sys

site = sys.argv[1]
ping_count = 4
process = subprocess.Popen(['ping', site, '-c', str(ping_count)],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT)
returncode = process.wait()
print('ping returned {0}'.format(returncode))
print(process.stdout.read())

示例:

$ python ping.py google.com         <-- ping successful
ping returned 0
PING google.com (195.64.213.27) 56(84) bytes of data.
64 bytes from cache.google.com (195.64.213.27): icmp_seq=1 ttl=57 time=59.8 ms
64 bytes from cache.google.com (195.64.213.27): icmp_seq=2 ttl=57 time=2.43 ms
64 bytes from cache.google.com (195.64.213.27): icmp_seq=3 ttl=57 time=77.0 ms
64 bytes from cache.google.com (195.64.213.27): icmp_seq=4 ttl=57 time=43.8 ms

--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 2.439/45.802/77.096/27.658 ms

$ python ping.py asdasdas.com       <-- DNS resolved, but site is down
ping returned 1
PING asdasdas.com (69.172.201.208) 56(84) bytes of data.

--- asdasdas.com ping statistics ---
4 packets transmitted, 0 received, 100% packet loss, time 3024ms

$ python ping.py asdasdasdasda.com  <-- DNS failed
ping returned 2
ping: unknown host asdasdasdasda.com

答案 1 :(得分:1)

正如您的错误消息所述,ping已完成非零退出状态。这可能意味着,例如提供的IP地址无法访问或您传入了错误的参数。

来自ping手册页(http://linux.die.net/man/8/ping):

  

如果ping根本没有收到任何回复数据包,它将以代码1退出。如果指定了数据包计数和截止时间,并且在截止日期到达之前收到的数据包数量少于它,则它也将退出代码1.在其他错误上,它以代码2退出。否则它以代码0退出。这使得可以使用退出代码来查看主机是否存活。

您可以尝试抓住CalledProcessError并查看output中包含的内容。 看看https://docs.python.org/2/library/subprocess.html#subprocess.check_output