转载请注明原始出处:http://blog.csdn.net/a464057216/article/details/47678781
后续此博客不再更新,欢迎大家搜索关注微信公众号“测开之美”,测试开发工程师技术修炼小站,持续学习持续进步。
多线程编程中,经常会遇到怎么让程序优雅地停止的问题,举一个简单的例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Written by - CSDN:Mars Loo的博客
import threading, time
def printA():
while True:
print 'a'
time.sleep(1)
def printB():
while True:
print 'b'
time.sleep(1)
if __name__ == '__main__':
try:
a = threading.Thread(target = printA)
b = threading.Thread(target = printB)
a.start()
b.start()
a.join()
b.join()
except Exception, exc:
print exc
printA和printB两个线程分别不断的隔1s打印字母a和b,但是这样的程序跑起来以后用Ctrl+C根本杀不掉,只有关掉终端窗口或者kill掉这个进程:
mars@mars-Ideapad-V460:~/test$ python ctrl.py
a
b
^C^Ca
b
^C^Ca
b
^Ca
b
a
b
如果把两个进程都设置成守护进程,倒是可以用Ctrl+C终止程序:
# Written by - CSDN:Mars Loo的博客
a = threading.Thread(target = printA)
b = threading.Thread(target = printB)
a.setDaemon(True)
a.start()
b.setDaemon(True)
b.start()
while True:
pass
执行结果:
mars@mars-Ideapad-V460:~/test$ python ctrl.py
a
b
b
a
^CTraceback (most recent call last):
File "ctrl.py", line 25, in <module>
while True:
KeyboardInterrupt
但是上面的方法又会在屏幕上输出丑陋的traceback信息,下面介绍一种优雅的方法:
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Written by - CSDN:Mars Loo的博客
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 'You choose to stop me.'
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, exc:
print exc
执行结果:
mars@mars-Ideapad-V460:~/test$ python ctrl.py
a
b
b
a
a
b
^CYou choose to stop me.
如果觉得我的文章对您有帮助,欢迎关注我(CSDN:Mars Loo的博客)或者为这篇文章点赞,谢谢!