2
votes

I've set up a stdout redirect using the class Redir in test.py (below).

The output should show both print statements in the textbox. But currently only "Output1" is sent to the textbox and "Output2" printed in the console behind.

I wondered if there was a way to redirect the stdout of a subprocess? I've tried using subprocess.PIPE and the Redir class itself but can't get it right.

Note: Eventually, the Popen call won't be calling a python file, so I'm not able to just get the string from Test2. I'm also unfortunately restricted to Python 2.6.

Thanks!

test.py:

import sys
from Tkinter import *
import subprocess

class Redir(object):
    def __init__(self, textbox):
        self.textbox = textbox
        self.fileno = sys.stdout.fileno

    def write(self, message):
        self.textbox.insert(END, str(message))

class RedirectGUI(object):
    def __init__(self):
        # Create window - Ignore this bit.
        # ================================
        self.root = Tk()
        self.btn = Button(self.root, text="Print!", command=self.print_stuff, state=NORMAL)
        self.btn.pack()
        self.textbox = Text(self.root)
        self.textbox.pack()

        # Setup redirect
        # ==============
        self.re = Redir(self.textbox)
        sys.stdout = self.re

        # Main window display
        # ===================
        self.root.mainloop()

    def print_stuff(self):
        subprocess.Popen(["python", "test2.py"], stdout=self.re)
        print "Output1"

if __name__ == "__main__":
    RedirectGUI()

test2.py:

class Test2(object):
    def __init__(self):
        print "Output2"

if __name__ == "__main__":
    Test2()
1

1 Answers

2
votes

You could try this so see if you get the "Output2"

task = subprocess.Popen(["python", "test2.py"], stdout=subprocess.PIPE)
print task.communicate()

If you do, send it to the textbox :)