Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the output from os.system()? [duplicate]

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)

like image 341
KamilDev Avatar asked Dec 23 '15 08:12

KamilDev


1 Answers

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.

like image 134
Mike Müller Avatar answered Oct 23 '22 23:10

Mike Müller