簡體   English   中英

重定向子流程標准輸出

[英]Redirecting subprocess stdout

我已經在test.py中使用類Redir設置了標准輸出重定向(如下)。

輸出應在文本框中顯示兩個打印語句。 但是目前只有“ Output1”發送到文本框,“ Output2”打印在后面的控制台中。

我想知道是否有一種方法可以重定向子流程的標准輸出? 我嘗試使用subprocess.PIPE和Redir類本身,但無法正確處理。

注意:最終,Popen調用不會調用python文件,因此我無法僅從Test2獲取字符串。 不幸的是,我也僅限於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”

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

如果您這樣做,請將其發送到文本框:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM