Redirecting subprocess stdout

落花浮王杯 提交于 2019-12-11 10:46:17

问题


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:


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 :)



来源:https://stackoverflow.com/questions/16966231/redirecting-subprocess-stdout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!