subprocess.Popen 不重定向生成进程的输出

subprocess.Popen doesn't redirect output of the spawned process

我无法将使用 subprocess.Popen 创建的进程的输出重定向到我选择的文件。以下是我正在做的事情:

#popen_test.py 
import sys, os, subprocess, time, signal

process_log = open('process.log','w')
process = subprocess.Popen([<path_to_python_binary>,"process.py"], stdout=process_log, stderr=process_log, preexec_fn=os.setsid) #launching the sub process
time.sleep(10) #waiting for sometime; this allows the sub process to print some statements. See below
process_log.flush()
os.killpg(process.pid,signal.SIGTERM)
process_log.close()

而且,这就是我的 process.py 的样子。它基本上是定期在标准输出上打印一些语句:

#process.py    
import sys,os,time
print "Initially..."
while True:
    print "Hello World"
    time.sleep(1)

进程正在启动,正如我所看到的,使用 ps,但输出不会进入 process.log--文件仍然是空的。知道我可能做错了什么吗?

print "hello world"之后好像是"block-buffering mode"-related issue. Run the script using python -u or add sys.stdout.flush()

默认情况下,

sys.stdout 重定向到文件时会完全缓冲。 print "hello world" 将字符串添加到标准输出缓冲区。如果您终止子进程,则不会刷新缓冲区,因此如果缓冲区在进程仍然 运行 时没有溢出,则不会向文件写入任何内容(缓冲区大小 4K-8K:os.fstat(sys.stdout.fileno()).st_blksize)。

注意:child 进程使用文件描述符的副本,即,您可以在 parent 中关闭 process_log 文件 一旦 Popen() returns -- 它对 child.

没有影响