簡體   English   中英

如何使用 python 同時多次運行 python 腳本並在完成后全部終止

[英]How to run a python script multiple times simultaneously using python and terminate all when one has finished

也許這是一個非常簡單的問題,但我是並發新手。 我想做一個 python 腳本來同時運行foo.py 10 次時間限制為 60 秒,然后自動中止。 該腳本是一種非確定性算法,因此所有執行都需要不同的時間,其中一個將在其他執行之前完成。 一旦第一個結束,我想節省執行時間,算法的 output,然后殺死進程的 rest。

我已經看到這個問題同時運行 python 腳本的多個實例,它看起來非常相似,但是我怎樣才能添加時間限制和第一個完成執行時的可能性,殺死進程的 rest?

先感謝您。

我建議使用線程庫,因為使用它您可以將線程設置為守護線程,這樣如果主線程出於任何原因退出,其他線程就會被殺死。 這是一個小例子:

#Import the libs...
import threading, time

#Global variables... (List of results.)
results=[]


#The subprocess you want to run several times simultaneously...
def run():
 #We declare results as a global variable.
 global results
 #Do stuff...
 results.append("Hello World! These are my results!")


n=int(input("Welcome user, how much times should I execute run()? "))
#We run the thread n times.
for _ in range(n):
 #Define the thread.    
 t=threading.Thread(target=run)
 #Set the thread to daemon, this means that if the main process exits the threads will be killed.
 t.setDaemon(True)
 #Start the thread.
 t.start()

#Once the threads have started we can execute tha main code.
#We set a timer...
startTime=time.time()
while True:
 #If the timer reaches 60 s we exit from the program.
 if time.time()-startTime>=60:
  print("[ERROR] The script took too long to run!")
  exit()
 #Do stuff on your main thread, if the stuff is complete you can break from the while loop as well. 
 results.append("Main result.")
 break

#When we break from the while loop we print the output.
print("Here are the results: ")
for i in results:
 print(f"-{i}")

這個例子應該可以解決你的問題,但是如果你想在主線程上使用阻塞命令,計時器會失敗,所以你需要稍微調整一下這段代碼。 如果您想這樣做,將代碼從主線程的循環移動到新的 function(例如def main():並從主線程的主線程執行 rest。這個例子可以幫助你:

def run():
 pass

#Secondary "main" thread.
def main():
 #Start the rest of the threads ( in this case I just start 1).
 localT=threading.Thread(target=run)
 localT.setDaemon(True)
 localT.start()
 #Do stuff.
 pass

#Actual main thread...
t=threading.Thread(target=main)
t.setDaemon(True)
t.start()
#Set up a timer and fetch the results you need with a global list or any other method...
pass

現在,您應該不惜一切代價避免全局變量,因為有時它們可能有點錯誤,但由於某種原因,線程庫不允許您從線程返回值,至少我不知道任何方法。 我認為還有其他多處理庫可以讓您返回值,但我對它們一無所知,所以我無法向您解釋任何事情。 無論如何,我希望這對你有用。

-更新:好的,我正忙於編寫代碼,沒有閱讀帖子中的評論,抱歉。 您仍然可以使用此方法,但不是在線程內編寫代碼,而是執行另一個腳本。 您可以將其作為模塊導入,也可以將其作為腳本實際運行,這里有一個問題可以幫助您: 如何在另一個文件中運行一個 python 文件?

暫無
暫無

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

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