开发者

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

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 开发者_StackOverflowrun via the os.system() command in Python?


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


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


Redirect stderr as well as stdout.


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.


I've found this answer while looking for a pythonic way to execute commands. The accepted answer has a deadlock if command waits for input. But it is not enough to just reverse read with write as you will have the deadlock if command writes larger output before it reads. The way to avoid this issue is to use p.communicate or even better Popen.run that does it for you.

Here are some examples:

To discard or read outputs:

>>> import subprocess
>>> r = subprocess.run("pip install fastai".split(), capture_output=True)
# you can ignore the result to discard it or read it
>>> r.stdout  
# and gets stdout as bytes

To pass something to the process use input:

>>> import subprocess
>>> subprocess.run("tr h H".split(), capture_output=True, text=True, input="hello").stdout
'Hello'

If you really don't want to deal with stdout, you can pass subprocess. DEVNULL to stdout and stderr as follows:

>>> import subprocess as sp
>>> sp.run("pip install fastai".split(), stdout=sp.DEVNULL, stderr=sp.DEVNULL).returncode
0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜