在运行完整脚本的Python中停止多进程,可以使用以下方法:
multiprocessing
模块创建多进程时,可以通过调用子进程的terminate()
方法来停止子进程。例如:import multiprocessing
import time
def worker():
while True:
print("Working...")
time.sleep(1)
if __name__ == "__main__":
process = multiprocessing.Process(target=worker)
process.start()
time.sleep(5) # 运行5秒后停止子进程
process.terminate()
在上述示例中,我们创建了一个名为worker
的函数作为子进程的入口点。在主进程中,我们创建了一个Process
对象,并通过start()
方法启动子进程。然后,主进程等待5秒后调用子进程的terminate()
方法来停止子进程的执行。
multiprocessing
模块中的Pool
类来管理多个进程,并使用terminate()
方法停止所有子进程。例如:import multiprocessing
import time
def worker(index):
while True:
print(f"Working in process {index}...")
time.sleep(1)
if __name__ == "__main__":
pool = multiprocessing.Pool(processes=4)
for i in range(4):
pool.apply_async(worker, args=(i,))
time.sleep(5) # 运行5秒后停止所有子进程
pool.terminate()
在上述示例中,我们使用Pool
类创建了一个具有4个进程的进程池,并通过apply_async()
方法将worker
函数提交给进程池进行执行。然后,主进程等待5秒后调用进程池的terminate()
方法来停止所有子进程的执行。
这些方法可以在运行完整脚本的Python中停止多进程。请注意,这些方法只是停止了子进程的执行,而不会终止主进程的执行。
云+社区沙龙online[数据工匠]
云+社区技术沙龙[第17期]
云原生正发声
企业创新在线学堂
DB TALK 技术分享会
腾讯技术创作特训营第二季第2期
DBTalk
云+社区技术沙龙[第11期]
领取专属 10元无门槛券
手把手带您无忧上云