I want to get output from os.system("nslookup google.com")
but instead I always get 0
, when printing it. Why is this, and how can I fix this? (Python 3, Mac)
(I looked at How to store the return value of os.system that it has printed to stdout in python? - But I didn't understand it ~ I'm new to python)
Use subprocess
:
import subprocess
print(subprocess.check_output(['nslookup', 'google.com']))
If the return code is not zero it will raise a CalledProcessError
exception:
try:
print(subprocess.check_output(['nslookup', 'google.com']))
except subprocess.CalledProcessError as err:
print(err)
os.system only returns the exit code of the command. Here 0
means success. Any other number stands for an operating-system-dependent error. The output goes to stdout of this process. subprocess intends to replace os.system
.
subprocess.check_output is a convenience wrapper around subprocess.Popen that simplifies your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With