简体   繁体   English

将subprocess.Popen与python一起使用时如何结束子进程?

[英]How to end the sub process when using subprocess.Popen with python?

I use a script to run two script. 我使用一个脚本来运行两个脚本。 the code like this: 像这样的代码:

import subprocess

subprocess.Popen("python a.py", shell=True)
subprocess.Popen("python b.py", shell=True)

but if I end the main script, the sub process of a.py and b.py are still runing. 但是如果我结束主脚本,则a.py和b.py的子进程仍在运行。 How to solve it? 怎么解决呢?

added: 添加:

the a.py and b.py is two server scripts. a.py和b.py是两个服务器脚本。 When I end the main script using ctrl+c,and the two servers is not end up.So how to end the all process when I end the main script? 当我使用ctrl + c结束主脚本时,两个服务器都没有结束。那么,当我结束主脚本时如何结束所有进程?

By killing the processes. 通过杀死进程。

import subprocess

p1 = subprocess.Popen("python a.py", shell=True)
p2 = subprocess.Popen("python b.py", shell=True)

# ... do things ...

p1.kill()
p2.kill()

You can also automate this with the atexit module: 您还可以使用atexit模块自动执行此操作:

import subprocess
import atexit

p1 = subprocess.Popen("python a.py", shell=True)
p2 = subprocess.Popen("python b.py", shell=True)
atexit.register(p1.kill)  # register for killing
atexit.register(p2.kill)

# ... do things ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM