重定向当前运行的 python 进程的标准输出

redirecting current runing python process' stdout

我有 python 代码 运行 垃圾邮件标准输出和标准错误的 C 代码。

我想抑制 stdout 和 stderr,而不能修改 C 代码。作为伪代码,大致是:

def external_api_I_cant_control():
    C code that outputs to stdout & stderr # this is not a subprocess 
                                           # call which I can redirect
                                           # its stdout & stderr. Rather,
                                           # it's a wrapper for it so there
                                           # is nothing I can do to control its
                                           # FD

def do_stuff():
    external_api_I_cant_control()

我的代码正在 运行 使用 python bla.py,因此,我可以使用 python bla.py 2>/dev/null 重定向 stderr,但这并不能解决我的问题,因为一些垃圾邮件发送至 stdout,我无法重定向 stdout - 因为我需要一些。

是否可以在我的代码中执行 shell stdout 重定向的等效操作?

到目前为止我试过了:

  1. contextlib.redirect_stdout
  2. sys.stdoutsys.__stdout__ 替换为 open(os.devnull, 'w')

我想要的结果相当于将我的 bla.py 分成 3 份,然后 运行 像这样

python bla0.output.is.legit.py
python bla1.output.should.be.disregarded.py &> /dev/null
python bla2.output.is.legit.again.py

实现这一目标的方法是什么?

这是 os.dup2() 的工作。您想要的代码包括三个阶段:

  • 备份原始标准输出和标准错误
  • 用指向 /dev/null
  • 的文件句柄替换 stdout 和 stderr
  • 正在恢复备份(在 运行 您想要的代码之后)。

# create a backup of stdout and stderr
orig_stdout_fd = os.dup(1)
orig_stderr_fd = os.dup(2)

# make the original stdout and stderr point to /dev/null
devnull = open('/dev/null', 'r+')
os.dup2(devnull.fileno(), 1)
os.dup2(devnull.fileno(), 2)

# run your C code here
os.write(1, b"This would normally go to stdout\n")

# put the originals back
os.dup2(orig_stdout_fd, 1)
os.dup2(orig_stderr_fd, 2)
os.close(orig_stdout_fd)
os.close(orig_stderr_fd)