在不访问代码的情况下删除 Python 中所有子进程的输出 [英] Remove output of all subprocesses in Python without access to code
问题描述
在 Python 中我正在使用
In Python I'm using
sys.stdout = None
在一些我无法控制的电话之前.这些调用可能会调用一些写入标准输出的子进程.
before some calls that I don't control. These calls may call some subprocesses that write to stdout.
如何避免此子进程调用写入标准输出?
How can I avoid this subprocesses calls to write to stdout?
同样,我没有调用子进程的代码的所有权.似乎 subprocess.Popen(和类似的)不尊重 sys.stdout.
Again, I don't have ownership of the code that calls the subprocess. It seems subprocess.Popen (and similar) doesn't honor sys.stdout.
推荐答案
您可以使用抑制 stdout
和 stderr<的自定义函数替换
subprocess.Popen
/代码>:
You could replace subprocess.Popen
with a custom function that suppresses stdout
and stderr
:
import subprocess
import inspect
def Popen(*args, **kwargs):
sig = inspect.signature(real_popen)
bound_args = sig.bind(*args, **kwargs).arguments
bound_args['stdout'] = subprocess.DEVNULL
bound_args['stderr'] = subprocess.DEVNULL
return real_popen(**bound_args)
real_popen = subprocess.Popen
subprocess.Popen = Popen
警告:
如果您的代码试图读取进程的输出,它将失败.
If you have code that attempts to read the process's output, it will fail.
这篇关于在不访问代码的情况下删除 Python 中所有子进程的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!