Redirecting stdio from a command in os.system(

2019-01-09 11:18发布

问题:

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?

回答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



回答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")


回答3:

Redirect stderr as well as stdout.



回答4:

If you want to completely eliminate the console that launches with the python program, you can save it with the .pyw extension.

I may be misunderstanding the question, though.