spacepaste

  1.  
  2. #####################################################################
  3. # redirectText.py
  4. #
  5. # Created by Mike Driscoll
  6. #
  7. # Contact: mike@pythonlibrary.org
  8. # Website: http://www.blog.pythonlibrary.org
  9. #
  10. # Tested on Windows XP, Python 2.5.2, wxPython 2.8.9.1 (msw-unicode)
  11. #####################################################################
  12. import sys
  13. import os
  14. import wx
  15. import threading
  16. import time
  17. #import SomeModule1
  18. class RedirectText(object):
  19. def __init__(self,aWxTextCtrl):
  20. self.out=aWxTextCtrl
  21. def write(self,string):
  22. wx.CallAfter(self.out.WriteText, string)
  23. from subprocess import Popen, PIPE
  24. from threading import Thread
  25. from threading import Lock
  26. from Queue import Queue, Empty
  27. io_q = Queue()
  28. processList=[]
  29. lock = Lock()
  30. class StreamWatcher:
  31. def stdout_watcher(self, identifier, stream):
  32. #for line in stream:
  33. for line in iter(stream.readline,b''):
  34. print line
  35. if not stream.closed:
  36. stream.close()
  37. print "-i- Thread Terminating : ", identifier,"\n"
  38. def stderr_watcher(self, identifier, stream):
  39. #for line in stream:
  40. for line in iter(stream.readline,b''):
  41. print (identifier, line)
  42. if not stream.closed:
  43. stream.close()
  44. print "-i- Thread Terminating : ", identifier, "\n"
  45. import sys
  46. import subprocess
  47. import random
  48. import time
  49. import threading
  50. import Queue
  51. class AsynchronousFileReader(threading.Thread):
  52. '''
  53. Helper class to implement asynchronous reading of a file
  54. in a separate thread. Pushes read lines on a queue to
  55. be consumed in another thread.
  56. '''
  57. def __init__(self, fd, queue):
  58. assert isinstance(queue, Queue.Queue)
  59. assert callable(fd.readline)
  60. threading.Thread.__init__(self)
  61. self._fd = fd
  62. self._queue = queue
  63. def run(self):
  64. '''The body of the tread: read lines and put them on the queue.'''
  65. for line in iter(self._fd.readline, ''):
  66. self._queue.put(line)
  67. def eof(self):
  68. '''Check whether there is no more content to expect.'''
  69. isDead = not self.is_alive() and self._queue.empty()
  70. if isDead:
  71. self.join()
  72. self._fd.close()
  73. class MyGUI(wx.Frame):
  74. def __init__(self):
  75. wx.Frame.__init__(self, None, wx.ID_ANY, "wxPython Redirect Tutorial")
  76. # Add a panel so it looks the correct on all platforms
  77. panel = wx.Panel(self, wx.ID_ANY)
  78. log = wx.TextCtrl(panel, wx.ID_ANY, size=(300,100),
  79. style = wx.TE_MULTILINE|wx.TE_READONLY|wx.HSCROLL)
  80. btn = wx.Button(panel, wx.ID_ANY, 'Push me!')
  81. self.Bind(wx.EVT_BUTTON, self.onButton, btn)
  82. # Add widgets to a sizer
  83. sizer = wx.BoxSizer(wx.VERTICAL)
  84. sizer.Add(log, 1, wx.ALL|wx.EXPAND, 5)
  85. sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
  86. panel.SetSizer(sizer)
  87. # redirect text here
  88. redir=RedirectText(log)
  89. sys.stdout=redir
  90. sys.stderr=redir
  91. self.stdout_queue = Queue.Queue()
  92. self.stderr_queue = Queue.Queue()
  93. def onButton(self, event):
  94. print ("-i- this is printed from GUI module itself")
  95. #SomeModule1.printSomething()
  96. PathToCurrentPythonInterpreter = os.path.abspath(os.path.join(sys.prefix, "python.exe"))
  97. modPath = os.path.abspath( os.path.join(os.path.abspath(os.path.dirname(__file__)),'SomeModule1.py') )
  98. print PathToCurrentPythonInterpreter
  99. print modPath
  100. proc = Popen([PathToCurrentPythonInterpreter, modPath], stdout=PIPE, stderr=PIPE, bufsize=1)
  101. #m=StreamWatcher()
  102. #n=StreamWatcher()
  103. #Thread(target=m.stdout_watcher, name='stdout-watcher', args=('STDOUT', proc.stdout, self.stdout_queue)).start()
  104. #Thread(target=n.stderr_watcher, name='stderr-watcher', args=('STDERR', proc.stderr, self.stderr_queue)).start()
  105. Thread(target=self.printerThread, name='stderr-watcher').start()
  106. stdout_reader = AsynchronousFileReader(proc.stdout, self.stdout_queue).start()
  107. stderr_reader = AsynchronousFileReader(proc.stderr, self.stderr_queue).start()
  108. #self.processList.append(proc)
  109. def printerThread(self):
  110. print "printer!"
  111. # Check the queues if we received some output (until there is nothing more to get).
  112. while True:
  113. # Show what we received from standard output.
  114. while not self.stdout_queue.empty():
  115. line = self.stdout_queue.get()
  116. print 'Received line on standard output: ' + repr(line)
  117. # Show what we received from standard error.
  118. while not self.stderr_queue.empty():
  119. line = self.stderr_queue.get()
  120. print 'Received line on standard error: ' + repr(line)
  121. # Sleep a bit before asking the readers again.
  122. time.sleep(.1)
  123. # Run the program
  124. if __name__ == "__main__":
  125. app = wx.PySimpleApp()
  126. frame = MyGUI().Show()
  127. app.MainLoop()
  128.