TraceCollector.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # win32traceutil like utility for Pythonwin
  2. import _thread
  3. import win32trace, win32event, win32api
  4. from pywin.framework import winout
  5. outputWindow = None
  6. def CollectorThread(stopEvent, file):
  7. win32trace.InitRead()
  8. handle = win32trace.GetHandle()
  9. # Run this thread at a lower priority to the main message-loop (and printing output)
  10. # thread can keep up
  11. import win32process
  12. win32process.SetThreadPriority(win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_BELOW_NORMAL)
  13. try:
  14. while 1:
  15. rc = win32event.WaitForMultipleObjects((handle, stopEvent), 0, win32event.INFINITE)
  16. if rc == win32event.WAIT_OBJECT_0:
  17. # About the only char we can't live with is \0!
  18. file.write(win32trace.read().replace("\0", "<null>"))
  19. else:
  20. # Stop event
  21. break
  22. finally:
  23. win32trace.TermRead()
  24. print("Thread dieing")
  25. class WindowOutput(winout.WindowOutput):
  26. def __init__(self, *args):
  27. winout.WindowOutput.__init__(*(self,)+args)
  28. self.hStopThread = win32event.CreateEvent(None, 0, 0, None)
  29. _thread.start_new(CollectorThread, (self.hStopThread, self))
  30. def _StopThread(self):
  31. win32event.SetEvent(self.hStopThread)
  32. self.hStopThread = None
  33. def Close(self):
  34. self._StopThread()
  35. winout.WindowOutput.Close(self)
  36. # def OnViewDestroy(self, frame):
  37. # return winout.WindowOutput.OnViewDestroy(self, frame)
  38. # def Create(self, title=None, style = None):
  39. # rc = winout.WindowOutput.Create(self, title, style)
  40. return rc
  41. def MakeOutputWindow():
  42. # Note that it will not show until the first string written or
  43. # you pass bShow = 1
  44. global outputWindow
  45. if outputWindow is None:
  46. title = "Python Trace Collector"
  47. # queueingFlag doesnt matter, as all output will come from new thread
  48. outputWindow = WindowOutput(title, title)
  49. # Let people know what this does!
  50. msg = """\
  51. # This window will display output from any programs that import win32traceutil
  52. # win32com servers registered with '--debug' are in this category.
  53. """
  54. outputWindow.write(msg)
  55. # force existing window open
  56. outputWindow.write('')
  57. return outputWindow
  58. if __name__=='__main__':
  59. MakeOutputWindow()