簡體   English   中英

Python運行多個進程

[英]Python running multiple processes

我有一個腳本( a.py ),該腳本需要多次調用另一個腳本( b.py ),每次執行b.py都需要1分鍾。 如果我在for循環中運行,這會花費很多時間。

我想知道如何優化這一點,以減少時間。 任何幫助或建議都將非常有幫助。

源代碼:

# a.py
import os

if __name__ == '__main__':
    inputs = ['file1', 'file2', 'file3', 'file4']
    script_path = 'b.py'

    # Some logging statements. 
    for infile in inputs:
    os.system("{} -i {}".format(script_path, infile))  


# b.py
    # take arguments
    # perform some operations
    # log the execution

到目前為止,我一直在使用os.system來調用其他腳本。 如何並行調用腳本b.py n次?

您無法通過這種方式對其進行優化。 如果要為列表中的每個項目運行腳本b,則迭代是執行此操作的唯一方法。 可能您可以更改腳本b的內容以使其運行更快,但這是另一個問題。

您可以使用muliprocessing.Process並行運行它:

from multiprocessing import Process

inputs = ['file1', 'file2', 'file3', 'file4']
script_path = 'b.py'

def run(script, name):
    os.system("{} -i {}".format(script, name))  

if __name__ == '__main__':
    inputs = ['file1', 'file2', 'file3', 'file4']
    script_path = 'b.py'
    for infile in inputs:
        p = Process(target=run, args=(script_path, infile))
        p.start()
    p.join()

注意 :使用os.system從Python腳本執行Python腳本不是很優雅。 您應該將腳本b.py修改為一個模塊,該模塊同時提供其主要功能以及函數或類。 然后,您可以導入b並使用這些函數或類。

暫無
暫無

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

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