将 popen 输出重定向到 python 中的文件

redirecting popen output to file in python

我看到很多答案 stdout=file 会重定向到一个文件。但我有几个疑问。

  1. 为什么 >file 不起作用。

    subprocess.Popen([SCRIPT, "R", ">", FILE, "2>", "/dev/null"])
    
  2. 这样可以吗

    with open(FILE,'w+') as f:
        subprocess.Popen([SCRIPT, stdout=f]
        f.close()
    

在我的例子中,我试图 运行 无限循环中的脚本(不会停止)并且有一些其他进程监视其输出。

脚本是否在 f 关闭后继续写入。如果是,它是如何工作的?

我想你一定要试试,

with open(FILE,'w+') as f:
    subprocess.Popen([SCRIPT, stdout=f, stderr=f])

因为 subprocess 不允许使用 > 来重定向输出和错误消息,来自文档:

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, DEVNULL, an existing file descriptor (a positive integer), an existing file object, and None.

PIPE indicates that a new pipe to the child should be created. DEVNULL indicates that the special file os.devnull will be used. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent.

Additionally, stderr can be STDOUT, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.


您应该使用以下代码:

with open(FILE, 'w+') as f:
    subprocess.Popen([SCRIPT, 'R'],  stdout=f, stderr=subprocess.DEVNULL))

因为您正在使用with,所以不需要关闭文件。