python - 重定向当前正在运行的 python 进程的 stdout

标签 python stdout io-redirection

我有运行 C 代码的 python 代码,这些代码会发送垃圾邮件 stdout 和 stderr。

我想抑制 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 code>,但这并不能解决我的问题,因为一些垃圾邮件是发送到 stdout 的,而我无法重定向 stdout - 因为我需要其中一些。 p>

是否可以在我的代码中执行相当于 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() 的工作。您想要的代码由三个阶段组成:

  • 备份原始 stdout 和 stderr
  • 用指向 /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)

关于python - 重定向当前正在运行的 python 进程的 stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68716139/

相关文章:

shell - 如何在 fish shell 中打印到标准错误?

java - 输入重定向到键盘输入

c - scanf如何判断是否阻塞?

python - 如何将图像写入数据存储?

python - 如何使用 Python/Pandas 从日期字段按月、日分组

c - 我应该在 C 中将 stdout 和 stdin 设置为无缓冲吗?

linux - 从 mbuffer 获取 stderr 到变量

python - Python Dataframe 子集的平均值

php - 插件设置 WordPress 3.8.1 在 Google App-engine SDK 上运行

java - Eclipse 中的 I/O 重定向?