2016-04-28 96 views

回答

0

如果你不需要從批處理命令的輸出,你可以簡單地

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

閱讀Threadhttps://docs.python.org/2/library/threading.html#thread-objects
閱讀subprocesshttps://docs.python.org/2/library/subprocess.html
文檔爲什麼shell=True is dangeroushttps://docs.python.org/2/library/subprocess.html#frequently-used-arguments

你可能喜歡用ThreadPoolmultiprocessing庫,如果你不需要很多的控制權系統。關於將函數映射到多個線程的multiprocessing.ThreadPool.map示例,請參見http://chriskiehl.com/article/parallelism-in-one-line/

相關問題