我写了一个简单的脚本来记录我的连接状态(因为我想记录我的ISP断开连接的频率)。当可以访问IP时,以下脚本可以使用:
import subprocess
from datetime import datetime
cmd = ['/bin/ping -c 1 -w2 8.8.8.8 > /dev/null 2>&1']
response = subprocess.check_call(cmd, shell=True, stderr=subprocess.STDOUT)
time_stamp = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
log_file = "ping_check.log"
if response == 0:
log_entry = time_stamp + ': up\n'
with open(log_file, "a") as logfile:
logfile.write(log_entry)
else:
log_entry = time_stamp + ': down\n'
with open(log_file, "a") as logfile:
logfile.write(log_entry)
但是,当我使用无法访问的IP运行脚本时,我得到以下内容:
shw@ventura:~/Desktop$ ./ping_check_test.py
Traceback (most recent call last):
File "./ping_check_test.py", line 12, in <module>
response = subprocess.check_call(cmd, shell=True, stderr=subprocess.STDOUT)
File "/usr/lib/python2.7/subprocess.py", line 540, in check_call
raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/bin/ping -c 1 -w2 10.0.0.1 > /dev/null 2>&1']' returned non-zero exit status 1
我该如何处理?我也看了check_output
,但这似乎也不是我想做的。
答案 0 :(得分:2)
您可以捕获异常:
try:
response = subprocess.check_call(cmd, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
print "Could not ping"
response = err.returncode
但在您的情况下,您可能希望使用subprocess.call()
function;它与subprocess.check_call()
完全相同,但当返回状态不为0时,不会引发异常:
response = subprocess.call(cmd, shell=True, stderr=subprocess.STDOUT)