这个问题困扰了很久,尝试过很多办法,个别确实有效,但是效果不稳定。。。。 下方这个 目前测试 比较好用
import sys, threading, time
class TraceThread(threading.Thread):
def __init__(self, *args, **keywords):
threading.Thread.__init__(self, *args, **keywords)
self.killed = False
def start(self):
self._run = self.run
self.run = self.settrace_and_run
threading.Thread.start(self)
def settrace_and_run(self):
sys.settrace(self.globaltrace)
self._run()
def globaltrace(self, frame, event, arg):
return self.localtrace if event == ‘call’ else None
def localtrace(self, frame, event, arg):
if self.killed and event == ‘line’:
raise SystemExit()
return self.localtrace
def f(str1):
while True:
print(str1+‘:1’)
time.sleep(2)
print(str1+‘:2’)
time.sleep(2)
print(str1+‘:3’)
time.sleep(2)
t = TraceThread(target=f, args=(‘test’,))
t.start()
print t.is_alive()
time.sleep(2.5)