0

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?

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.