我已经使用test.py中的Redir类设置了stdout重定向(如下所示)。
输出应在文本框中显示两个打印语句。但是目前只有"Output1“被发送到textbox,而"Output2”则打印在后面的控制台中。
我想知道是否有办法重定向子进程的stdout?我尝试过使用subprocess.PIPE和Redir类本身,但是无法正确地实现它。
注意:最终,Popen调用将不会调用python文件,因此我无法只从Test2获取字符串。不幸的是,我也仅限于Python2.6。
谢谢!
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()发布于 2013-06-06 15:40:34
你可以试试这个,看看你能不能得到"Output2“
task = subprocess.Popen(["python", "test2.py"], stdout=subprocess.PIPE)
print task.communicate()如果需要,将其发送到textbox :)
https://stackoverflow.com/questions/16966231
复制相似问题