将命令提示符输出重定向到 python 生成的窗口 [英] Redirect command prompt output to a python generated window

查看:29
本文介绍了将命令提示符输出重定向到 python 生成的窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Developed a script which builds a project using msbuild. I have GUI developed using wxpython which has a button on which when user clicks would build a project using msbuild. Now, i want to open a status window when user click on that button and shows all the output which shows in the command prompt and command prompt should not be displayed i.e,redirecting the command prompt output to the user GUI status window. My build script is,

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

推荐答案

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

I actually wrote about this a few years ago on my blog where I created a script to redirect ping and traceroute to my wxPython app: http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/

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

Basically you create a simple class to redirect stdout to and pass it an instance of a TextCtrl. It ends up looking something like this:

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

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

然后当我写我的 ping 命令时,我是这样做的:

Then when I wrote my ping command, I did this:

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 允许文本打印"(即重定向)到标准输出.没有它,在命令完成之前文本不会显示.我希望一切都说得通.

The main thing to look at is the stdout parameter in your subprocess call and the wx.Yield() is important too. The Yield allows the text to get "printed" (i.e. redirected) to stdout. Without it, the text won't show up until the command is finished. I hope that all made sense.

这篇关于将命令提示符输出重定向到 python 生成的窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆