简体   繁体   中英

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 run via the os.system() command in Python?

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

在UNIX系统上,您可以将stderr和stdout重定向到/ dev / null作为命令本身的一部分。

os.system(cmd + "> /dev/null 2>&1")

重定向标准错误和标准错误。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM