views:

869

answers:

2

I have created a program that prints results on command line. (It is server and it prints log on command line.)

Now, I want to see the same result to GUI .

How can I redirect command line results to GUI?

Please, suggest a trick to easily transform console application to simple GUI.

NOTE:It should work on Linux And Windows.

+3  A: 

You could create a script wrapper that runs your command line program as a sub process, then add the output to something like a text widget.

from tkinter import *
import subprocess as sub
p = sub.Popen('./script',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()

root = Tk()
text = Text(root)
text.pack()
text.insert(END, output)
root.mainloop()

where script is your program. You can obviously print the errors in a different colour, or something like that.

EDIT: Added a mainloop after comment.

Greg Reynolds
I tried it on linux, its not working,please suggest a solution..
TheMachineCharmer
It's missing a root.mainloop() at the end to start the event loop. apart from that, it looks like it should work.
mavnn
Yes I didn't have a linux system to try it on so it was all from memory...
Greg Reynolds
A: 

Redirecting stdout to a write() method that updates your gui is one way to go, and probably the quickest - although running a subprocess is probably a more elegant solution.

Only redirect stderr once you're really confident it's up and working, though!

Example implimentation (gui file and test script):

test_gui.py:

from Tkinter import *
import sys
sys.path.append("/path/to/script/file/directory/")

class App(Frame):
    def run_script(self):
        sys.stdout = self
        ## sys.stderr = self
        try:
            del(sys.modules["test_script"])
        except:
            ## Yeah, it's a real ugly solution...
            pass
        import test_script
        test_script.HelloWorld()
        sys.stdout = sys.__stdout__
        ## sys.stderr = __stderr__

    def build_widgets(self):
        self.text1 = Text(self)
        self.text1.pack(side=TOP)
        self.button = Button(self)
        self.button["text"] = "Trigger script"
        self.button["command"] = self.run_script
        self.button.pack(side=TOP)

    def write(self, txt):
        self.text1.insert(INSERT, txt)

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.build_widgets()

root = Tk()
app = App(master = root)
app.mainloop()

test_script.py:

print "Hello world!"

def HelloWorld():
    print "HelloWorldFromDef!"
mavnn