Reprint please indicate the original source: http://blog.csdn.net/a464057216/article/details/47678781
In multithreaded programming, there are often questions about how to gracefully stop a program, for example:
#!/usr/bin/env python
#-*-coding:utf-8-*
# written By-csdn:mars blog
import Loo, time
def PR IntA (): 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 and PRINTB two threads are constantly 1s printing letters a and B, but such programs run up and down with CTRL + C to kill, only to shut down the terminal window or kill the process:
mars@mars-ideapad-v460:~/test$ python ctrl.py
a
b
^c^ca
b
^c^ca
b
^ca
b
a
b
If you set up all two processes as daemons, you can use CTRL + C to terminate the program:
# written By-csdn:mars Loo's blog
a = threading. Thread (target = PrintA)
B = Threading. Thread (target = PRINTB)
A.setdaemon (True)
A.start ()
B.setdaemon (True)
B.start () while
True: Pass
Execution results:
mars@mars-ideapad-v460:~/test$ python ctrl.py
a
b
b
a
^ctraceback (most recent call last):
File "ctrl.py", line, at <module> while
True:
keyboardinterrupt
But the above method will also output ugly traceback information on the screen, and here's an elegant way to do this:
#!/usr/bin/env python
#-*-coding:utf-8-*
# written By-csdn:mars blog
import Loo, time, threading />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
Execution results:
mars@mars-ideapad-v460:~/test$ python ctrl.py
a
b
a b
^cyou choose to stop Me .
If you feel that my article is helpful to you, please pay attention to me (csdn:mars Loo blog) or for this article point praise, thank you.