analbeard
analbeard

Reputation: 45

Handling subprocess.check_call's errors

I wrote a simple script to log the state of my connection (as I want to log how often my ISP drops the connection anyway). The script below works when the IP is reachable:

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)

However, when I run the script with an unreachable IP, I get the following:

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

How can I go about handling this? I looked at check_output too, but that doesn't seem to do what I want either.

Upvotes: 0

Views: 1122

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124488

You can catch the exception:

try:
    response = subprocess.check_call(cmd, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
    print "Could not ping"
    response = err.returncode

but in your case you probably want to use the subprocess.call() function instead; it does exactly the same thing as subprocess.check_call() but doesn't raise an exception when the return status is not 0:

response = subprocess.call(cmd, shell=True, stderr=subprocess.STDOUT)

Upvotes: 2

Related Questions