p中的Python子进程

2024-04-26 10:38:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想并行运行许多进程,并能在任何时候执行stdout。我该怎么做?我需要为每个subprocess.Popen()调用运行线程吗,什么?


Tags: 进程stdout线程subprocesspopen
3条回答

你可以用一根线来做。

假设有一个脚本可以随机打印行:

#!/usr/bin/env python
#file: child.py
import os
import random
import sys
import time

for i in range(10):
    print("%2d %s %s" % (int(sys.argv[1]), os.getpid(), i))
    sys.stdout.flush()
    time.sleep(random.random())

您希望在输出可用时立即收集它,可以在POSIX系统上使用^{}作为@zigg suggested

#!/usr/bin/env python
from __future__ import print_function
from select     import select
from subprocess import Popen, PIPE

# start several subprocesses
processes = [Popen(['./child.py', str(i)], stdout=PIPE,
                   bufsize=1, close_fds=True,
                   universal_newlines=True)
             for i in range(5)]

# read output
timeout = 0.1 # seconds
while processes:
    # remove finished processes from the list (O(N**2))
    for p in processes[:]:
        if p.poll() is not None: # process ended
            print(p.stdout.read(), end='') # read the rest
            p.stdout.close()
            processes.remove(p)

    # wait until there is something to read
    rlist = select([p.stdout for p in processes], [],[], timeout)[0]

    # read a line from each process that has output ready
    for f in rlist:
        print(f.readline(), end='') #NOTE: it can block

一个更可移植的解决方案(应该在Windows、Linux、OSX上工作)可以为每个进程使用读线程,请参见Non-blocking read on a subprocess.PIPE in python

以下是基于^{}的解决方案,适用于Unix和Windows:

#!/usr/bin/env python
from __future__ import print_function
import io
import os
import sys
from subprocess import Popen

ON_POSIX = 'posix' in sys.builtin_module_names

# create a pipe to get data
input_fd, output_fd = os.pipe()

# start several subprocesses
processes = [Popen([sys.executable, 'child.py', str(i)], stdout=output_fd,
                   close_fds=ON_POSIX) # close input_fd in children
             for i in range(5)]
os.close(output_fd) # close unused end of the pipe

# read output line by line as soon as it is available
with io.open(input_fd, 'r', buffering=1) as file:
    for line in file:
        print(line, end='')
#
for p in processes:
    p.wait()

还可以使用^{}同时从多个子进程收集stdout:

#!/usr/bin/env python
import sys
from twisted.internet import protocol, reactor

class ProcessProtocol(protocol.ProcessProtocol):
    def outReceived(self, data):
        print data, # received chunk of stdout from child

    def processEnded(self, status):
        global nprocesses
        nprocesses -= 1
        if nprocesses == 0: # all processes ended
            reactor.stop()

# start subprocesses
nprocesses = 5
for _ in xrange(nprocesses):
    reactor.spawnProcess(ProcessProtocol(), sys.executable,
                         args=[sys.executable, 'child.py'],
                         usePTY=True) # can change how child buffers stdout
reactor.run()

Using Processes in Twisted

不需要为每个进程运行线程。您可以查看每个进程的stdout流而不阻塞它们,并且只有在它们有数据可供读取时才从中读取。

不过,如果你不打算这样做的话,你必须小心不要意外地堵住它们。

相关问题 更多 >