Python 中 Bash 子进程的并行处理
顺序运行子进程可能会影响应用程序的性能。要同时执行多个 bash 命令,您可以利用 Python 中的线程和子进程模块。
直接使用子进程
虽然线程对于并行处理来说似乎是必要的,但事实并非如此必需的。您可以使用 subprocess.Popen 函数并行启动进程:
<code class="python">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 commands in parallel processes = [Popen(cmd, shell=True) for cmd in commands] # Perform other tasks while processes run # Wait for completion for p in processes: p.wait()</code>
限制并发子进程
要限制并发进程的数量,请考虑使用多处理.dummy.Pool 模块,使用线程模拟多处理:
<code class="python">from functools import partial from multiprocessing.dummy import Pool from subprocess import call pool = Pool(2) # Limit to two concurrent commands # Iterate over commands and return codes for i, returncode in enumerate(pool.imap(partial(call, shell=True), commands)): if returncode != 0: print("%d command failed: %d" % (i, returncode))</code>
无池限制
您还可以在没有线程池的情况下限制并发:
<code class="python">from subprocess import Popen from itertools import islice max_workers = 2 processes = (Popen(cmd, shell=True) for cmd in commands) running_processes = list(islice(processes, max_workers)) # Start initial processes while running_processes: for i, process in enumerate(running_processes): if process.poll() is not None: # 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</code>
以上是如何在 Python 中同时执行多个 Bash 命令?的详细内容。更多信息请关注PHP中文网其他相关文章!