簡體   English   中英

Python:同時運行多個功能

[英]Python: running multiple functions concurrently

我正在使用 Pycharm 來運行我的 Python 代碼。 我有一個 function 將多個 excel 文件組合在一個文件夾中並寫入一個 csv 文件。 我有 5 個文件夾,我想為其創建 5 個 csv 文件。 現在,我按順序運行,即一個文件夾接一個文件夾。 這需要相當長的時間。 我還有另一個選擇:運行相同的代碼,但使用 5 個不同的 Pycharm 項目。 這行得通。 但我想知道是否有辦法在 1 個項目中同時運行這個 function 5 次? 我的偽代碼是:

combine("folder1", "csvfile1")
combine("folder2", "csvfile2")
combine("folder3", "csvfile3")
combine("folder4", "csvfile4")
combine("folder5", "csvfile5")

嘗試使用multiprocessing將 map 和 function combine分離內核並異步運行。 這是一個例子 -

#!pip install multiprocessing
import multiprocessing as mp

fo = ["folder1","folder2","folder3","folder4"]
fi = ["csvfile1","csvfile2","csvfile3","csvfile4"]

def combine(a,b):
    #YOUR CODE HERE
    print("Completed: ",a,'->',b)

pool = mp.Pool(processes=4) #Set this to the max number of cores you have
results = [pool.apply_async(combine, args=(x)) for x in zip(fo,fi)]

Completed:  folder2 -> csvfile2
Completed:  folder1 -> csvfile1
Completed:  folder3 -> csvfile3
Completed:  folder4 -> csvfile4

function 的每次迭代都是異步和並行運行的,以便更好地利用您的資源。

在此處輸入圖像描述


正如Furas指出的那樣,您現在可以使用starmap (及其異步版本),因為multiprocessing現在支持它( 在 3.3 版中添加)。 這有助於將參數元組直接映射到 function 而不是迭代和應用zip

results = pool.starmap_async(combine, zip(fo,fi)) #async version
results = pool.starmap(combine, zip(fo,fi)) #sync version

如果你有一個return作為你的 function 的一部分並且你想要檢索這些值,對於同步版本你可以簡單地從result中獲取它但對於異步版本,你將需要一個result.get()

Akshay Sehgal 已經向您解釋了如何使用它。 我只添加了很少的信息。

您可以使用map() (對於單個參數)或starmap() (對於許多參數)將其寫得更短

 results = pool.starmap_async(combine, zip(fo,fi))

如果您使用async版本,那么您可能需要.get()來等待所有結果

def combine(a,b):
    return b

results = pool.starmap_async(combine, zip(fo,fi))
print(results.get())

如果你將使用非異步版本那么你不需要 `.get()

def combine(a,b):
    return b

results = pool.starmap(combine, zip(fo,fi))
print(results)

進程可能會同時print() ,它可能會混合來自不同進程的消息,因此最好在打印前創建一個字符串

print(f"Completed: {a} -> {b}")

import multiprocessing as mp

fo = ["folder1","folder2","folder3","folder4"]
fi = ["csvfile1","csvfile2","csvfile3","csvfile4"]

def combine(a,b):
    #YOUR CODE HERE
    print(f"Completed: {a} -> {b}") # it is good to create one string to display all as one string without strings from other processes
    return b

pool = mp.Pool(processes=4)

# async version

results = pool.starmap_async(combine, zip(fo,fi))
# it needs `.get()` because it is `async`
print(results.get())

# non-async version

results = pool.starmap(combine, zip(fo,fi))
# it doesn't needs `.get()` because it is not `async`
print(results)

暫無
暫無

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

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