Python的subprocess
模塊本身并不直接支持多線程處理,因為它主要用于啟動和管理外部命令或進程
multiprocessing
模塊創(chuàng)建多個進程,每個進程可以運行一個子進程。這樣可以實現(xiàn)并行執(zhí)行多個外部命令或任務。import subprocess
from multiprocessing import Process
def run_subprocess(command):
process = Process(target=subprocess.run, args=(command,))
process.start()
return process
commands = ["echo 'Command 1'", "echo 'Command 2'", "echo 'Command 3'"]
processes = [run_subprocess(command) for command in commands]
for process in processes:
process.join()
concurrent.futures.ThreadPoolExecutor
)來限制并發(fā)線程的數(shù)量。這對于I/O密集型任務(如網(wǎng)絡請求、文件讀寫等)非常有用,因為過多的線程可能會導致資源競爭和性能下降。import subprocess
from concurrent.futures import ThreadPoolExecutor
def run_subprocess(command):
return subprocess.run(command, shell=True, check=True)
commands = ["echo 'Command 1'", "echo 'Command 2'", "echo 'Command 3'"]
with ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(run_subprocess, commands))
請注意,這兩種方法都不是在同一個進程中運行多個子進程,而是通過創(chuàng)建多個進程或?qū)⑷蝿仗峤唤o線程池來實現(xiàn)的。這是因為Python的全局解釋器鎖(GIL)限制了在同一進程中同時執(zhí)行多個線程的能力。