python 守护线程和loggin模块
1 #coding=utf8 2 3 import threading 4 import time 5 import logging 6 7 logging.basicConfig( 8 level=logging.DEBUG, 9 format='[%(levelname)s]-(%(threadName)s)-%(message)s', 10 ) 11 12 def worker(): 13 logging.debug('starting') 14 #print 'I am worker:' 15 time.sleep(2) 16 logging.debug('ending') 17 18 19 def my_service(): 20 logging.debug('starting') 21 #print 'I am service:' 22 time.sleep(1) 23 logging.debug('ending') 24 25 t = threading.Thread(name='worker-by leon',target=worker) 26 t.setDaemon(True) #False阻塞主进程,True不阻塞 27 t.start() 28 t.join(3) #等待守护线程退出,join的时间大于线程睡眠时间,所以isAlive()的值为False 29 30 31 d = threading.Thread(name='service-by leon', target=my_service) 32 d.setDaemon(True) 33 d.start() 34 35 logging.debug(t.isAlive()) 36 d.join() 37 #不显示ending因为worker守护线程结束之前,主线程或其他线程已经退出 38 ''' 39 显示 40 [DEBUG]-(worker-by leon)-starting 41 [DEBUG]-(worker-by leon)-ending 42 [DEBUG]-(MainThread)-False 43 [DEBUG]-(service-by leon)-starting 44 [DEBUG]-(service-by leon)-ending 45 '''