python中多进程任务单单依靠ctrl+c无法直接关闭任务
这里我使用signal库来完成关闭多进程任务
下面贴代码
import threading, time, signal
import sys
def printA():
while True:
print('a')
time.sleep(1)
def printB():
while True:
print('b')
time.sleep(1)
def quit(signum, frame):
print('所有进程已关闭')
sys.exit()
if __name__ == '__main__':
try:
# 开始捕获信号
signal.signal(signal.SIGINT, quit)
signal.signal(signal.SIGTERM, quit)
a = threading.Thread(target = printA)
b = threading.Thread(target = printB)
a.setDaemon(True)
a.start()
b.setDaemon(True)
b.start()
while True:
pass
except Exception as exc:
print(exc)
核心代码为
try:
signal.signal(signal.SIGINT, quit)
signal.signal(signal.SIGTERM, quit)
except Exception as exc:
print(exc)
有这几行代码,可以在任意方式创建的多线程中关闭进程
欢迎大家关注我的博客爱吃回锅肉的胖子技术文章我会先发布到我的个人博客中