简体   繁体   English

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

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

I am able to capture the output of a processed called by ' Popen in real time using the following code: 我可以使用以下代码实时捕获' 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()

This works great. 这很好。 However, I now have multiple processes running using the code below, so I need to capture the stdout to a file for each process: 但是,我现在使用下面的代码运行多个进程,因此我需要将每个进程的标准输出捕获到文件中:

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)

Including for line in iter(p.stdout.readline,''):... code keeps the code executing in the first loop only. for line in iter(p.stdout.readline,''):...包含for line in iter(p.stdout.readline,''):...代码使代码仅在第一个循环中执行。

How can I capture the stdout (and presumably the stderr ) in real time of each process executed inside my loop to a file? 我如何实时捕获循环到文件中的每个进程的stdout (大概是stderr )?

Pass a new file object to subprocess.Popen each time you call it. 将一个新的文件对象传递给subprocess.Popen每次调用时都要打开。 This allows you to divert stdout to a separate file for each process. 这使您可以将每个进程的stdout转移到单独的文件中。 Here is an example 这是一个例子

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()

When I run that I get 3 separate files 当我运行时,我得到了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's stdin and stdout arguments accept file objects so you could just pass the opened file in there. Popen的stdin和stdout参数接受文件对象,因此您可以在其中传递打开的文件。

From the docs : 文档

stdin, stdout and stderr specify the executed program's standard input, standard output and standard error file handles, respectively. stdin,stdout和stderr分别指定执行程序的标准输入,标准输出和标准错误文件句柄。 Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object , and None. 有效值为PIPE,现有文件描述符(正整数), 现有文件对象和无。 PIPE indicates that a new pipe to the child should be created. PIPE指示应创​​建到子级的新管道。 [...] [...]

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

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