Reputation: 237
I'm working on using subprocess.check_output to call ping command and get some output. The script will catch the wrong domain name. However, the output of the ping command will always print out on its own. When there's no exception, the output will not print out on its own.
hostname = "somewrongdomain.com" # This domain will not connect
try:
response = (subprocess.check_output(["ping", "-c 1", self.hostname]).decode("utf-8")
print(response)
except subprocess.TimeoutExpired as e:
ping_rating = 0
except subprocess.CalledProcessError as e:
ping_rating = 0
#do something else
The output I'm getting:
$ python3 test.py
ping: sendto: No route to host
Is there any way to NOT print the output(ping: sendto: No route to host) when the exception is caught?
Upvotes: 0
Views: 179
Reputation: 1044
As written in the documentation subprocess.check_output
only captures STDOUT
.
To also capture standard error in the result, use
stderr=subprocess.STDOUT
:
>>> subprocess.check_output(
... "ls non_existent_file; exit 0",
... stderr=subprocess.STDOUT,
... shell=True)
'ls: non_existent_file: No such file or directory\n'
Upvotes: 2