Python—将多个Popen子进程的标准输出实时捕获到一个文件中
我能够使用以下代码实时捕获由“Python—将多个Popen子进程的标准输出实时捕获到一个文件中,python,subprocess,Python,Subprocess,我能够使用以下代码实时捕获由“Popen调用的已处理数据的输出: p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in iter(p.stdout.readline,''): sys.stdout.write(line) output, error = p.communicate()
Popen
调用的已处理数据的输出:
p = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for line in iter(p.stdout.readline,''):
sys.stdout.write(line)
output, error = p.communicate()
这很有效。但是,我现在使用下面的代码运行多个进程,因此我需要为每个进程将标准输出捕获到一个文件中:
for mapped_file in range(1,3):
#Fire the command in parallel
stdout = open(outfile + '.stdout', 'w')
p = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout_list.append(stdout)
process_list.append(p)
#for line in iter(p.stdout.readline,''):
# stdout.write(line)
#Wait for all processes to continue
while len(process_list) > 0:
for process in process_list:
#Loop through the process to wait until all tasks finished
if not process.poll() is None:
output, error = process.communicate()
#Remove the process from the list because it has finished
process_list.remove(process)
#Sleep for 1 second in between iterations
time.sleep(1)
包括iter中的行(p.stdout.readline“”):…
代码只在第一个循环中执行代码
如何实时捕获循环中执行到文件的每个进程的
stdout
(可能还有stderr
)呢?Popen的stdin和stdout参数接受文件对象,这样您就可以将打开的文件传递到其中
发件人:
stdin、stdout和stderr指定执行程序的标准
输入、标准输出和标准错误文件句柄。
有效值是管道,一个现有的文件描述符(正数)
整数),现有文件对象,且无。管道表示一个新的
应创建到子级的管道。[……]
每次调用新文件对象时,将其传递给
subprocess.Popen
。这允许您将stdout
转移到每个进程的单独文件中。这里有一个例子
import subprocess
procs = []
for p in range(3):
args = ['echo',"A Message from process #%d" % p]
#Funnel stdout to a file object, using buffering
fout = open("stdout_%d.txt" % p,'w')
p = subprocess.Popen(args,stdout=fout,bufsize=-1)
procs.append(p)
#Wait for all to finish
for p in procs:
p.communicate()
当我运行时,我得到3个独立的文件
ericu@eric-phenom-linux:~/Documents$ python write_multiple_proc_to_file.py
ericu@eric-phenom-linux:~/Documents$ ls -l stdout_*
-rw-rw-r-- 1 ericu ericu 26 Feb 23 09:59 stdout_0.txt
-rw-rw-r-- 1 ericu ericu 26 Feb 23 09:59 stdout_1.txt
-rw-rw-r-- 1 ericu ericu 26 Feb 23 09:59 stdout_2.txt
ericu@eric-phenom-linux:~/Documents$ cat stdout_*.txt
A Message from process #0
A Message from process #1
A Message from process #2
ericu@eric-phenom-linux:~/Documents$
我需要添加
bufsize
关键字才能真正了解实时性。谢谢很好用。stdout=file
为+1。在Popen()
之后调用fout.close()。调用p.communicate()
(PIPE
未使用)是没有意义的p.wait()
在这里更合适。@Brett:bufsize
在这里没有用(PIPE
)stdout=file
在文件描述符级别工作。如果子进程在stderr上产生足够的输出,则第一个代码示例可能会死锁。如果任何子进程在stdout或stderr上产生足够的输出,则第二个代码示例可能会死锁。