Python:并行执行cat子进程

时间:2014-05-12 14:13:15

标签: python shell subprocess python-multithreading

我正在远程服务器上运行多个cat | zgrep命令并单独收集它们的输出以供进一步处理:

class MainProcessor(mp.Process):
    def __init__(self, peaks_array):
        super(MainProcessor, self).__init__()
        self.peaks_array = peaks_array

    def run(self):
        for peak_arr in self.peaks_array:
            peak_processor = PeakProcessor(peak_arr)
            peak_processor.start()

class PeakProcessor(mp.Process):
    def __init__(self, peak_arr):
        super(PeakProcessor, self).__init__()
        self.peak_arr = peak_arr

    def run(self):
        command = 'ssh remote_host cat files_to_process | zgrep --mmap "regex" '
        log_lines = (subprocess.check_output(command, shell=True)).split('\n')
        process_data(log_lines)

然而,这会导致子进程('ssh ... cat ...')命令的顺序执行。第二个峰值等待第一个完成,依此类推。

如何修改此代码,以便子进程调用并行运行,同时仍然可以为每个单独收集输出?

2 个答案:

答案 0 :(得分:33)

您既不需要multiprocessing也不需要threading并行运行子流程,例如:

#!/usr/bin/env python
from subprocess import Popen

# run commands in parallel
processes = [Popen("echo {i:d}; sleep 2; echo {i:d}".format(i=i), shell=True)
             for i in range(5)]
# collect statuses
exitcodes = [p.wait() for p in processes]

它同时运行5个shell命令。注意:此处既不使用线程也不使用multiprocessing模块。没有必要在shell命令中添加&号&Popen不等待命令完成。您需要明确调用.wait()

方便,但没有必要使用线程来收集子进程的输出:

#!/usr/bin/env python
from multiprocessing.dummy import Pool # thread pool
from subprocess import Popen, PIPE, STDOUT

# run commands in parallel
processes = [Popen("echo {i:d}; sleep 2; echo {i:d}".format(i=i), shell=True,
                   stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
             for i in range(5)]

# collect output in parallel
def get_lines(process):
    return process.communicate()[0].splitlines()

outputs = Pool(len(processes)).map(get_lines, processes)

相关:Python threading multiple bash subprocesses?

这里的代码示例在同一个线程中同时从多个子进程输出:

#!/usr/bin/env python3
import asyncio
import sys
from asyncio.subprocess import PIPE, STDOUT

@asyncio.coroutine
def get_lines(shell_command):
    p = yield from asyncio.create_subprocess_shell(shell_command,
            stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    return (yield from p.communicate())[0].splitlines()

if sys.platform.startswith('win'):
    loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows
    asyncio.set_event_loop(loop)
else:
    loop = asyncio.get_event_loop()

# get commands output in parallel
coros = [get_lines('"{e}" -c "print({i:d}); import time; time.sleep({i:d})"'
                    .format(i=i, e=sys.executable)) for i in range(5)]
print(loop.run_until_complete(asyncio.gather(*coros)))
loop.close()

答案 1 :(得分:-1)

另一种方法(而不是将shell进程放在后台的其他建议)是使用multithreading.

您拥有的run方法会执行以下操作:

thread.start_new_thread ( myFuncThatDoesZGrep)

要收集结果,您可以执行以下操作:

class MyThread(threading.Thread):
   def run(self):
       self.finished = False
       # Your code to run the command here.
       blahBlah()
       # When finished....
       self.finished = True
       self.results = []

在多线程的链接中运行如上所述的线程。当你的线程对象有myThread.finished == True时,你可以通过myThread.results收集结果。