I’m trying to get output from a python multiprocessing Process displayed in a Tkinter gui.
I can send output from Processes via a gui to a command shell, for example by running the fllowing tiny script at a shell prompt:
from multiprocessing import Process
import sys
def myfunc(text):
print text
sys.stdout.flush()
def f1():
p1 = Process(target = myfunc, args = ("Surprise",))
p1.start()
def f2():
p2 = Process(target = myfunc, args = ("Fear",))
p2.start()
def fp():
myfunc("... and an almost fanatical devotion to the Pope")
a = Tk()
b1 = Button(a, text="Process 1", command=f1)
b1.grid(row=0, column=0, pady=10, padx=10, sticky=SE)
b2 = Button(a, text="Process 2", command=f2)
b2.grid(row=0, column=1, pady=10, padx=10, sticky=SE)
b3 = Button(a, text="Parent", command=fp)
b3.grid(row=0, column=2, pady=10, padx=10, sticky=SE)
if __name__ == "__main__":
a.mainloop()
I can also send output from the parent to a Text box, for example by modifying the above by commenting out the flushing of stdout in myfunc
# sys.stdout.flush()
and adding immediately after the “b3.grid…” line the following:
class STDText(Text):
def __init__(self, parent, cnf={}, **kw):
Text.__init__(self, parent, cnf, **kw)
def write(self, stuff):
self.config(state=NORMAL)
self.insert(END, stuff)
self.yview_pickplace("end")
self.config(state=DISABLED)
messages = STDText(a, height=2.5, width=30, bg="light cyan", state=DISABLED)
messages.grid(row=1, column=0, columnspan=3)
sys.stdout = messages
However I can’t figure out how to send output from the Processes to the text box. Am I missing something simple?
You could redirect stdout/stderr to a StringIO in myfunc(), then send whatever gets written into that StringIO back to the parent (as suggested by unutbu). See my answer to this question for one way of doing this redirection.
Since that example does a bit more than you need, here’s a version that’s more aligned with your stated goals:
The usual caveats about security apply here (i.e., don’t do this unless you can trust the sender of these code snippets to not do anything stupid/malicious).
Also note that you can simplify this a lot if you don’t need to interpret an arbitrary mix of python expressions and statements. If you only need to call a top-level function that generates some outputs, something like this may be more appropriate: