ResourceWarning 将 os.devnull 作为文件打开并在 Python 中打开

ResourceWarning with opening os.devnull as a file and popen in Python

出于可比性原因,我使用 devnull 作为重定向标准输出的文件(Python 2.7 没有 subprocess.DEVNULL

subprocess.Popen(args, stdout=open('w', os.devnull))

但是在 Python 3.4 中,当我使用它时收到资源警告

foo.py:107: ResourceWarning: unclosed file <_io.TextIOWrapper name='/dev/null' mode='w' encoding='UTF-8'>

显然会发生资源泄漏。然而,这对 /dev/nullnul 有影响吗?我应该只抑制这个警告吗?

我需要 运行 这个过程在 popen 调用之后的一段未知时间,同时程序在做其他事情,所以 devnull 资源的上下文管理器将无法工作。

我想过用threading调用subprocess.popen并在进程结束时关闭文件,但是我必须同时与子进程交互,所以threading不会工作如此轻松。

我发现有一个名为 atexit 的标准库模块用于注册在程序终止时调用的函数。要将其与文件处理程序一起使用,您需要向其注册关闭方法。

例如

import atexit
devnull = open(os.devnull, 'w')
atexit.register(devnull.close)
subprocess.Popen(args, stdout=devnull)

现在不会有资源泄漏,因为程序终止时文件已关闭。