簡體   English   中英

Python運行以在Parralel中運行批處理命令

[英]Python run to run Batch Command in Parralel

我有一個列表,其中包含我的所有批處理命令。(超過1000個)計數我需要一次(並行)運行此列表5中的命令,如果任何一個完成,則第6個命令應該啟動。

你能幫忙嗎? 謝謝

如果不需要Batch命令的輸出,則只需

import subprocess
subprocess.Popen("command string here", shell=True) 

這將在此Python運行時附帶的shell中運行批處理代碼。

要並行運行,您只需跟蹤當前正在運行的數量即可。 我喜歡為此使用線程

import subprocess
from threading import Thread
import time

processing = 0

def call_batch(command):
    global processing
    process = subprocess.Popen("command string here", shell=True)
    process.wait()
    processing -= 1

if __name__ == "__main__":
    commands = []
    ##load commands

    for command in commands:
        if processing < 5:
            t = Thread(target=call_batch, args=(command))
            t.daemon = True
            t.start()
            processing += 1
        else:
            time.sleep(0.1) # I don't know how long you expect these commands to take so this is allowing a max of 5 * (1/0.1) = 50 per second

如果您來自其他編程背景,則會注意到缺少鎖。 這是因為全局解釋器鎖定。

如果您對Python了解很多,您會注意到我的建議使用shell=True 我建議這樣做,因為它在受信任的輸入上執行時很簡單並且沒有危險,但是OP應該根據情況決定是否使用shell=True

Thread閱讀: https : //docs.python.org/2/library/threading.html#thread-objects
閱讀subprocesshttps : //docs.python.org/2/library/subprocess.html
關於shell=True is dangerous為何shell=True is dangerous文檔: https : //docs.python.org/2/library/subprocess.html#frequently-used-arguments

如果您不需要對系統進行大量控制,則可以使用multiprocessing庫中的ThreadPool 有關將函數映射到多個線程的multiprocessing.ThreadPool.map的示例,請參閱http://chriskiehl.com/article/parallelism-in-one-line/大約一半。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM