2

我已经使用 test.py 中的类 Redir 设置了标准输出重定向(如下)。

输出应在文本框中显示两个打印语句。但目前只有“Output1”被发送到文本框,“Output2”打印在后面的控制台中。

我想知道是否有办法重定向子进程的标准输出?我尝试过使用 subprocess.PIPE 和 Redir 类本身,但无法正确使用。

注意:最终,Popen 调用不会调用 python 文件,所以我不能只从 Test2 获取字符串。不幸的是,我也仅限于 Python 2.6。

谢谢!

测试.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()

测试2.py:

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

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

1 回答 1

2

你可以试试这个,看看你是否得到“Output2”

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

如果你这样做,请将其发送到文本框:)

于 2013-06-06T15:40:34.953 回答