繁体   English   中英

Python-将多个Popen子进程的stdout实时捕获到文件中

[英]Python - Capturing stdout of a multiple Popen subprocesses in real time to a file

我可以使用以下代码实时捕获' 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)

for line in iter(p.stdout.readline,''):...包含for line in iter(p.stdout.readline,''):...代码使代码仅在第一个循环中执行。

我如何实时捕获循环到文件中的每个进程的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$ 

Popen的stdin和stdout参数接受文件对象,因此您可以在其中传递打开的文件。

文档

stdin,stdout和stderr分别指定执行程序的标准输入,标准输出和标准错误文件句柄。 有效值为PIPE,现有文件描述符(正整数), 现有文件对象和无。 PIPE指示应创​​建到子级的新管道。 [...]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM