【问题标题】:Python threading multiple bash subprocesses?Python线程化多个bash子进程?
【发布时间】:2013-01-10 02:30:44
【问题描述】:

如何使用线程和子进程模块来生成并行 bash 进程?当我在这里启动线程时,第一个答案是:How to use threading in Python?,bash 进程按顺序运行而不是并行运行。

【问题讨论】:

标签: python multithreading subprocess


【解决方案1】:

一个简单的线程示例:

import threading
import Queue
import commands
import time

# thread class to run a command
class ExampleThread(threading.Thread):
    def __init__(self, cmd, queue):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.queue = queue

    def run(self):
        # execute the command, queue the result
        (status, output) = commands.getstatusoutput(self.cmd)
        self.queue.put((self.cmd, output, status))

# queue where results are placed
result_queue = Queue.Queue()

# define the commands to be run in parallel, run them
cmds = ['date; ls -l; sleep 1; date',
        'date; sleep 5; date',
        'date; df -h; sleep 3; date',
        'date; hostname; sleep 2; date',
        'date; uname -a; date',
       ]
for cmd in cmds:
    thread = ExampleThread(cmd, result_queue)
    thread.start()

# print results as we get them
while threading.active_count() > 1 or not result_queue.empty():
    while not result_queue.empty():
        (cmd, output, status) = result_queue.get()
        print('%s:' % cmd)
        print(output)
        print('='*60)
    time.sleep(1)

请注意,有更好的方法可以做到这一点,但这并不太复杂。该示例为每个命令使用一个线程。当您想要执行诸如使用有限数量的线程来处理未知数量的命令之类的事情时,复杂性开始蔓延。一旦掌握了线程基础知识,那些更高级的技术似乎就不会太复杂。一旦掌握了这些技术,多处理就会变得更容易。

【讨论】:

    【解决方案2】:

    您不需要线程来并行运行子进程:

    from subprocess import Popen
    
    commands = [
        'date; ls -l; sleep 1; date',
        'date; sleep 5; date',
        'date; df -h; sleep 3; date',
        'date; hostname; sleep 2; date',
        'date; uname -a; date',
    ]
    # run in parallel
    processes = [Popen(cmd, shell=True) for cmd in commands]
    # do other things here..
    # wait for completion
    for p in processes: p.wait()
    

    要限制并发命令的数量,您可以使用使用线程并提供与使用进程的multiprocessing.Pool 相同的接口的multiprocessing.dummy.Pool

    from functools import partial
    from multiprocessing.dummy import Pool
    from subprocess import call
    
    pool = Pool(2) # two concurrent commands at a time
    for i, returncode in enumerate(pool.imap(partial(call, shell=True), commands)):
        if returncode != 0:
           print("%d command failed: %d" % (i, returncode))
    

    This answer demonstrates various techniques to limit number of concurrent subprocesses:它展示了基于 multiprocessing.Pool、concurrent.futures、threading + Queue 的解决方案。


    您可以在不使用线程/进程池的情况下限制并发子进程的数量:

    from subprocess import Popen
    from itertools import islice
    
    max_workers = 2  # no more than 2 concurrent processes
    processes = (Popen(cmd, shell=True) for cmd in commands)
    running_processes = list(islice(processes, max_workers))  # start new processes
    while running_processes:
        for i, process in enumerate(running_processes):
            if process.poll() is not None:  # the process has finished
                running_processes[i] = next(processes, None)  # start new process
                if running_processes[i] is None: # no new processes
                    del running_processes[i]
                    break
    

    在 Unix 上,您可以避免忙循环和block on os.waitpid(-1, 0), to wait for any child process to exit

    【讨论】:

    • @j-f-sebastian 有了Popen,我可以使用communicate()处理输出,这样更方便。但我发现 pool.map(Popen, cmds) 并没有真正限制产生的进程数量。难道我做错了什么?另一方面,我能够让 pool.map(call, cmds) 正常工作,但无法捕获其输出(返回代码除外)。有没有办法捕获 call() 的输出?
    • 抱歉,看起来 call() 的输出无法捕获。 :-/
    • @SaheelGodhane 创建一个等待子进程退出的函数,例如,在其中调用.communicate()。将 that 函数传递给 pool.map 而不是 PopenPopen 立即返回Popen 传递给pool.map 是没有意义的。如果有不清楚的地方;问一个单独的问题
    • 亲爱的塞巴斯蒂安,我正在尝试做类似的事情,即:首先运行一个子进程 p,一旦 p 运行,然后我调用第二个子进程 p2,我尝试在新的终端窗口中运行 p2 ,但我不能让它与subprocess.CREATE_NEW_CONSOLE 一起工作,因为这似乎只适用于Windows 机器。也许你可以帮帮我:(顺便说一下the post
    • @hunter_tech:答案中的代码示例无关紧要(线程之间没有共享任何内容)。
    猜你喜欢
    • 2018-02-20
    • 2011-10-17
    • 2014-01-26
    • 2019-03-09
    • 2018-10-27
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多