threads.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. __filename__ = "threads.py"
  2. __author__ = "Bob Mottram"
  3. __license__ = "AGPL3+"
  4. __version__ = "1.0.0"
  5. __maintainer__ = "Bob Mottram"
  6. __email__ = "bob@freedombone.net"
  7. __status__ = "Production"
  8. import threading
  9. import sys
  10. import trace
  11. import time
  12. class threadWithTrace(threading.Thread):
  13. def __init__(self, *args, **keywords):
  14. self._args, self._keywords = args, keywords
  15. threading.Thread.__init__(self, *self._args, **self._keywords)
  16. self.killed = False
  17. def start(self):
  18. self.__run_backup = self.run
  19. self.run = self.__run
  20. threading.Thread.start(self)
  21. def __run(self):
  22. sys.settrace(self.globaltrace)
  23. self.__run_backup()
  24. self.run = self.__run_backup
  25. def globaltrace(self, frame, event, arg):
  26. if event == 'call':
  27. return self.localtrace
  28. else:
  29. return None
  30. def localtrace(self, frame, event, arg):
  31. if self.killed:
  32. if event == 'line':
  33. raise SystemExit()
  34. return self.localtrace
  35. def kill(self):
  36. self.killed = True
  37. def clone(self,fn):
  38. return threadWithTrace(target=fn, \
  39. args=self._args, \
  40. daemon=True)