Redirecting stdio from a command in os.system() in Python

41,836

Solution 1

You could consider running the program via subprocess.Popen, with subprocess.PIPE communication, and then shove that output where ever you would like, but as is, os.system just runs the command, and nothing else.

from subprocess import Popen, PIPE

p = Popen(['command', 'and', 'args'], stdout=PIPE, stderr=PIPE, stdin=PIPE)

output = p.stdout.read()
p.stdin.write(input)

Much more flexible in my opinion. You might want to look at the full documentation: Python Subprocess module

Solution 2

On a unix system, you can redirect stderr and stdout to /dev/null as part of the command itself.

os.system(cmd + "> /dev/null 2>&1")
Share:
41,836
Leif Andersen
Author by

Leif Andersen

Updated on July 14, 2020

Comments

  • Leif Andersen
    Leif Andersen almost 4 years

    Usually I can change stdout in Python by changing the value of sys.stdout. However, this only seems to affect print statements. So, is there any way I can suppress the output (to the console), of a program that is run via the os.system() command in Python?

  • Xavier Combelle
    Xavier Combelle almost 14 years
    That don't do the job quote from docs.python.org/library/os.html#process-management os.system(command) Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.
  • Leif Andersen
    Leif Andersen almost 14 years
    Mmm...okay. So than the command is executed on the line P = Popen(...), yes? And it will only show the output when calling p.stdout.read()...yes? Thank you
  • Leif Andersen
    Leif Andersen almost 14 years
    Okay...the commands did run, but in a separate thread. Is there anyway I can either hault the program while the commands run, or keep it in the same thread? Thank you.
  • Blue Peppers
    Blue Peppers almost 14 years
    Simply, use p.wait(). However, apparently this can result in deadlocking when using PIPE stdout if the program generates enough output. See the full documentation at docs.python.org/library/subprocess.html#subprocess.Popen.wai‌​t . However, I think it should work..
  • Leif Andersen
    Leif Andersen almost 14 years
    Hmm...okay, thanks. Also, it appears that using p.communicate() (rather than p.stdout will help clear the pipe. Thanks.
  • spurra
    spurra about 5 years
    This was the answer I was looking for and should've been the accepted answer.