重定向子进程标准输出 [英] Redirecting subprocess stdout
问题描述
我使用 test.py 中的 Redir 类(如下)设置了标准输出重定向.
I've set up a stdout redirect using the class Redir in test.py (below).
输出应该在文本框中显示两个打印语句.但目前只有Output1"发送到文本框,Output2"打印在后面的控制台中.
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.
我想知道是否有办法重定向子进程的标准输出?我试过使用 subprocess.PIPE 和 Redir 类本身,但无法正确使用.
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.
注意:最终,Popen 调用将不会调用 python 文件,因此我无法仅从 Test2 获取字符串.不幸的是,我也仅限于 Python 2.6.
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.
谢谢!
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()
推荐答案
你可以试试这个,看看你是否得到了Output2"
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 :)
这篇关于重定向子进程标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!