21

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
  • 179,855
  • 19
  • 132
  • 245
KamilDev
  • 718
  • 2
  • 7
  • 21
  • 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

25

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
  • 82,630
  • 20
  • 166
  • 161
  • 5
    It works. But could you explain why os.system(command) doesn't print output? (I'm new to Python) – KamilDev Dec 23 '15 at 09:06
  • 1
    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. – user258532 Dec 30 '18 at 13:21
  • Use `subprocess` not `os.system`. – Mike Müller Dec 31 '18 at 08:29
  • I keep getting `FileNotFoundError: [Errno 2] No such file or directory:` with subprocess – Eduardo Reis Sep 25 '21 at 21:36
  • Try `shell=True` as argument. – Mike Müller Sep 28 '21 at 15:20
  • In some more detail, you want `subprocess.check_output(["ls", "-l"])` or `subprocess.check_output("ls -l", shell=True)`. If you try `subprocess.check_output("ls -l")` without `shell=True`, Python will look for a command named literally `ls -l` (like literally, `/usr/local/bin/"ls -l"`) and, of course, not finding it. (These things work differently on Windows, to the point where writing `subprocess` code which is properly OS-independent is challenging.) [You should generally avoid `shell=True` if you can.](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) – tripleee Apr 28 '23 at 03:46