将命令提示符重定向输出到python生成的窗口

时间:2013-03-18 06:39:19

标签: python python-2.7 wxpython

开发了一个使用msbuild构建项目的脚本。我使用wxpython开发了GUI,它有一个按钮,当用户点击时可以使用msbuild构建项目。现在,我想在用户单击该按钮时打开一个状态窗口,并显示在命令提示符和命令提示符下显示的所有输出,不应显示,即将命令提示符输出重定向到用户GUI状态窗口。我的构建脚本是,

def build(self,projpath)
    arg1 = '/t:Rebuild'
    arg2 = '/p:Configuration=Release'
    arg3 = '/p:Platform=x86'
    p = subprocess.call([self.msbuild,projpath,arg1,arg2,arg3])
    if p==1:
        return False
    return True

2 个答案:

答案 0 :(得分:4)

几年前我在博客上写了这篇文章,我创建了一个脚本,将ping和traceroute重定向到我的wxPython应用程序:http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/

基本上,您创建了一个简单的类来重定向stdout并将其传递给TextCtrl的一个实例。最终看起来像这样:

class RedirectText:
    def __init__(self,aWxTextCtrl):
        self.out=aWxTextCtrl

    def write(self,string):
        self.out.WriteText(string)

然后当我写下ping命令时,我这样做了:

def pingIP(self, ip):
    proc = subprocess.Popen("ping %s" % ip, shell=True, 
                            stdout=subprocess.PIPE) 
    print
    while True:
        line = proc.stdout.readline()                        
        wx.Yield()
        if line.strip() == "":
            pass
        else:
            print line.strip()
        if not line: break
    proc.wait()

要看的主要内容是子进程调用中的stdout参数,而wx.Yield()也很重要。 Yield允许文本被“打印”(即重定向)到stdout。没有它,文本将在命令完成后才会显示。我希望这一切都有道理。

答案 1 :(得分:1)

我做了如下改动,它对我有用。

def build(self,projpath):
    arg1 = '/t:Rebuild'
    arg2 = '/p:Configuration=Release'
    arg3 = '/p:Platform=Win32'
    proc = subprocess.Popen(([self.msbuild,projpath,arg1,arg2,arg3]), shell=True, 
                    stdout=subprocess.PIPE) 
    print
    while True:
        line = proc.stdout.readline()                        
        wx.Yield()
        if line.strip() == "":
            pass
        else:
            print line.strip()
        if not line: break
    proc.wait() 
相关问题