14

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)

OneCricketeer
  • 151,199
  • 17
  • 111
  • 216
KamilDev
  • 618
  • 1
  • 7
  • 20
  • 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`. – Eric Leschinski Jan 06 '21 at 15:43

1 Answers1

18

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.

Mike Müller
  • 77,540
  • 18
  • 155
  • 159