23

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)

1
  • Python's os.system("ls") only returns the exit_code for ls which is a unix integer status from the operating system for the process. 0 here means "no-error". Both the stdout and stderr of os.system is piped into your python program's stdout and stderr. So either you re-implement this stdout redirection manually, or use a different python function that does this work automatically for you, one example of many being subprocess. Commented Jan 6, 2021 at 15:43

1 Answer 1

26

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.

Sign up to request clarification or add additional context in comments.

6 Comments

It works. But could you explain why os.system(command) doesn't print output? (I'm new to Python)
os.system(command) prints output of command to the console, but it does not capture it! For example, files = os.system("ls") does not store the result in files.
Use subprocess not os.system.
I keep getting FileNotFoundError: [Errno 2] No such file or directory: with subprocess
Try shell=True as argument.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.