问题描述
通常我可以通过改变 sys.stdout
的值来改变 Python 中的标准输出.但是,这似乎只影响 print
语句.那么,有什么方法可以抑制通过 Python 中的 os.system()
命令运行的程序的输出(到控制台)?
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?
推荐答案
您可以考虑通过 subprocess.Popen
运行程序,与 subprocess.PIPE
通信,然后将该输出推送到您想要的任何位置,但按原样,os.system
只运行命令,不执行其他任何操作.
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)
在我看来要灵活得多.您可能需要查看完整文档:Python 子流程模块
Much more flexible in my opinion. You might want to look at the full documentation: Python Subprocess module
这篇关于在 Python 中从 os.system() 中的命令重定向 stdio的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!