Advertisement
Guest User

Stack Overflow answer for #24589156

a guest
Jul 6th, 2014
1,421
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.98 KB | None | 0 0
  1. import subprocess
  2.  
  3. from Tkinter import Tk, Button
  4. from Tkconstants import END
  5. import tkFileDialog
  6. import ScrolledText
  7. from threading import Thread
  8. from Queue import Queue
  9.  
  10. class RunThread(Thread):
  11.     def __init__(self, filepath):
  12.         super(RunThread, self).__init__()
  13.         self.filepath = filepath
  14.         self.output = Queue()
  15.         self.finished = False
  16.    
  17.     def run(self):
  18.         p = subprocess.Popen(['python', self.filepath],
  19.                              stdout=subprocess.PIPE,
  20.                              stderr=subprocess.STDOUT,
  21.                              )
  22.         for line in iter(p.stdout.readline, ''):
  23.             self.output.put(line)
  24.         self.finished = True
  25.  
  26. class Application(object):
  27.     run_thread = None
  28.     def run(self):
  29.         self.root = Tk()
  30.         self.code = ScrolledText.ScrolledText(self.root)
  31.         self.code.pack()
  32.         self.output = ScrolledText.ScrolledText(self.root)
  33.         self.output.pack()
  34.         self.run = Button(self.root, text="Run", command=self.run_script)
  35.         self.run.pack()
  36.         self.root.mainloop()
  37.        
  38.     def run_script(self):
  39.         if self.run_thread:
  40.             return
  41.         script = self.code.get(1.0, END)
  42.         filepath = tkFileDialog.asksaveasfilename()
  43.         if filepath:
  44.             if not filepath.endswith('.py'):
  45.                 filepath += '.py'
  46.             with open(filepath, 'w') as f:
  47.                 f.write(script)
  48.             self.run_thread = RunThread(filepath)
  49.             self.run_thread.start()
  50.             self.read_output()
  51.        
  52.     def read_output(self):
  53.         while not self.run_thread.output.empty():
  54.             line = self.run_thread.output.get()
  55.             self.output.insert(END, line)
  56.         if self.run_thread.finished:
  57.             self.output.insert(END, "%s Finished" % self.run_thread.filepath)
  58.             self.run_thread = None
  59.         else:
  60.             self.root.after(100, self.read_output)
  61.  
  62. Application().run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement