title: How to redirect in real time STDOUT from imported module to Tkinter Text Widget in python?
body: <p>I am trying to redirect stdout into a Tkinter Text widget in real time using Python 2.7.2 on Windows 7. In my code below, I intended to have a print statement appear in the Text widget every 2 seconds. What happens, instead, is that all 3 lines</p>
  
  <pre><code>Received sleep-command
  Going to sleep for 2 s
  Just woke up
  </code></pre>
  
  <p>appear simultaneously as soon as both sleep() and mod1.main() have been evaluated.</p>
  
  <p>Surprisingly (to me, at least) the problem disappears when I do not redirect stdout. That is, if I comment out the line</p>
  
  <pre><code>sys.stdout = StdoutRedirector(outputPanel)
  </code></pre>
  
  <p>IDLE displays the print statements in real time. Can somebody explain this to me and suggest a way to get around it? Thanks in advance!</p>
  
  <p>Here is my example code:</p>
  
  <p>mod1.py</p>
  
  <pre><code>import time
  import sys
  
  def main():
      print('Going to sleep for 2 s')
      time.sleep(2)
      print('Just woke up')
  </code></pre>
  
  <p>text_GUI.py</p>
  
  <pre><code>from Tkinter import *
  import sys
  import time
  import mod1
  
  old_stdout = sys.stdout
  
  class StdoutRedirector(object):
  
      def __init__(self, text_area):
          self.text_area = text_area
  
      def write(self, str):
          self.text_area.insert(END, str)
          self.text_area.see(END)
  
  def sleep():
      print('Received sleep-command')
      time.sleep(2)
      mod1.main()
  
  root = Tk()
  
  # Textbox
  outputPanel = Text(root, wrap='word', height = 11, width=50)
  outputPanel.grid(column=0, row=0, columnspan = 2, sticky='NSWE', padx=5, pady=5)
  sys.stdout = StdoutRedirector(outputPanel)
  
  # Sleep button
  sleepBtn = Button(root, text='Sleep', command=sleep)
  sleepBtn.grid(row=1, column=1, sticky='E', padx=5, pady=5)
  
  root.mainloop()
  
  sys.stdout = old_stdout
  </code></pre>