如何使用python同时多次运行python脚本,并在完成后终止所有脚本

如何使用python同时多次运行python脚本,并在完成后终止所有脚本,python,multithreading,parallel-processing,process,scripting,Python,Multithreading,Parallel Processing,Process,Scripting,也许这是一个非常简单的问题,但我对并发性是新手。我想做一个python脚本,在自动中止之前同时运行foo.py 10次,时间限制为60秒。该脚本是一个非确定性算法,因此所有执行都需要不同的时间,其中一个将在其他执行之前完成。一旦第一个进程结束,我希望节省执行时间、算法的输出,然后结束其余进程 我已经看到了这个问题,它看起来非常相似,但是我如何才能添加时间限制,以及第一个进程何时完成执行、何时终止其余进程的可能性 提前感谢您。我建议使用线程库,因为有了它,您可以将线程设置为守护线程,这样,如果主线

也许这是一个非常简单的问题,但我对并发性是新手。我想做一个python脚本,在自动中止之前同时运行foo.py 10次,时间限制为60秒。该脚本是一个非确定性算法,因此所有执行都需要不同的时间,其中一个将在其他执行之前完成。一旦第一个进程结束,我希望节省执行时间、算法的输出,然后结束其余进程

我已经看到了这个问题,它看起来非常相似,但是我如何才能添加时间限制,以及第一个进程何时完成执行、何时终止其余进程的可能性


提前感谢您。

我建议使用线程库,因为有了它,您可以将线程设置为守护线程,这样,如果主线程出于任何原因退出,其他线程都会被终止。下面是一个小例子:

#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}")
这个例子应该可以解决您的问题,但是如果您想在主线程上使用阻塞命令,计时器就会失败,所以您需要稍微调整一下代码。如果您想这样做,请将代码从主线程的循环移动到一个新函数,例如def main:并从main上的主线程执行其余线程。此示例可能会帮助您:

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脚本。我已经编辑了这个问题,所以没有歧义。你的问题可以用设计模式来解决。首先,谢谢你非常清晰和详细的回答,但我认为它不能完全满足我的需要。线程执行一个函数。如果其中一个线程结束,该函数将生成一个输出,我需要捕获该输出。在这一点上,我对其他线程不感兴趣,所以我想杀死它们hi@Biowav,我明白你的意思,但我认为可以从导入的文件捕获输出,我不确定如何捕获,因为我通常不使用它们,但我仍然认为你应该检查一下,您可能会发现一些有用的东西。您是否尝试过查看命令模式?终止线程不是正确的方法,因为在硬件级别,门会松动并可能损坏硬件