【问题标题】:wxpython GUI running a command-line programwxpython GUI 运行命令行程序
【发布时间】:2013-09-05 19:45:00
【问题描述】:

我已经搜索了一个小时,但找不到明确的答案。

我正在尝试编写一个 wxPython GUI 应用程序,它有一个启动命令行工具的按钮(全部在 Windows 上)。该工具运行大约需要 5 分钟,并在运行过程中产生输出。

我希望 GUI 有某种文本窗口,可以在输出发生时显示输出。我还想终止 GUI 以终止命令行进程。

我查看了线程和 Popen,但似乎无法找出它们之间的正确连接来完成这项工作。谁能指点我一个合理的例子?

【问题讨论】:

标签: python wxpython subprocess


【解决方案1】:

我写了一篇文章,其中我做了一些你所说的事情。我需要运行 ping 和 traceroute 并实时捕获它们的输出。这是文章:http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/

基本上你需要将标准输出重定向到一个文本控件,然后做这样的事情:

proc = subprocess.Popen("ping %s" % ip, shell=True, 
                            stdout=subprocess.PIPE) 
line = proc.stdout.readline()
print line.strip()

如您所见,我使用子进程开始 ping 并读取其标准输出。然后我使用 strip() 命令从行的开头和结尾删除多余的空格,然后再打印出来。当您进行打印时,它会被重定向到文本控件。

【讨论】:

    【解决方案2】:

    我在 GooeyPi 应用程序中的 wxPython 中执行此操作。它运行 pyInstaller 命令并在 textctrl 中逐行捕获输出。

    在主应用程序框架中,有一个调用OnSubmit的按钮:

    def OnSubmit(self, e):
        ...
         # this is just a list of what to run on the command line, something like [python, pyinstaller.py, myscript.py, --someflag, --someother flag]
        flags = util.getflags(self.fbb.GetValue())
        for line in self.CallInstaller(flags): # generator function that yields a line
            self.txtresults.AppendText(line) # which is output to the txtresults widget here
    

    CallInstaller 执行命令的实际运行,产生一行以及运行 wx.Yield(),因此屏幕不会冻结得太严重。您可以将其移至其自己的线程,但我没有打扰。

    def CallInstaller(self, flags):
            # simple subprocess.Popen call, outputs both stdout and stderr to pipe
            p = subprocess.Popen(flags, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            while(True): 
                retcode = p.poll() # waits for a return code, until we get one..
                line = p.stdout.readline() # we get any output
                wx.Yield() # we give the GUI a chance to breathe
                yield line # and we yield a line
                if(retcode is not None): # if we get a retcode, the loop ends, hooray!
                    yield ("Pyinstaller returned return code: {}".format(retcode))
                    break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 2013-06-25
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      相关资源
      最近更新 更多