代码之家  ›  专栏  ›  技术社区  ›  Bryan Oakley

wxPython:异步执行命令,在文本小部件中显示标准输出

  •  1
  • Bryan Oakley  · 技术社区  · 17 年前

    我正在寻找与我的答案相同的wxPython Tcl/Tk examples? . 具体来说,我想看一个如何创建几个按钮的示例,每个按钮在单击时运行一些外部命令。当进程运行时,我希望输出转到一个可滚动的wxPython小部件。

    进程运行时,GUI不应阻塞。例如,假设其中一个按钮可以启动开发任务,如构建或运行单元测试。

    3 回复  |  直到 9 年前
        1
  •  7
  •   FogleBird    17 年前

    这是一个完整的工作示例。

    import wx
    import functools
    import threading
    import subprocess
    import time
    
    class Frame(wx.Frame):
        def __init__(self):
            super(Frame, self).__init__(None, -1, 'Threading Example')
            # add some buttons and a text control
            panel = wx.Panel(self, -1)
            sizer = wx.BoxSizer(wx.VERTICAL)
            for i in range(3):
                name = 'Button %d' % (i+1)
                button = wx.Button(panel, -1, name)
                func = functools.partial(self.on_button, button=name)
                button.Bind(wx.EVT_BUTTON, func)
                sizer.Add(button, 0, wx.ALL, 5)
            text = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE|wx.TE_READONLY)
            self.text = text
            sizer.Add(text, 1, wx.EXPAND|wx.ALL, 5)
            panel.SetSizer(sizer)
        def on_button(self, event, button):
            # create a new thread when a button is pressed
            thread = threading.Thread(target=self.run, args=(button,))
            thread.setDaemon(True)
            thread.start()
        def on_text(self, text):
            self.text.AppendText(text)
        def run(self, button):
            cmd = ['ls', '-lta']
            proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
            for line in proc.stdout:
                wx.CallAfter(self.on_text, line)
    
    if __name__ == '__main__':
        app = wx.PySimpleApp()
        frame = Frame()
        frame.Show()
        app.MainLoop()
    
        2
  •  0
  •   kgiannakakis    17 年前

    单击按钮时启动线程:

    try:
        r = threading.Thread(target=self.mycallback)
        r.setDaemon(1)
        r.start()
    except:
        print "Error starting thread"
        return False
    

    使用wx.PostEvent和wx.lib.newevent将消息从回调发送到主线程。

    link 可能会有帮助。

        3
  •  0
  •   Jim Carroll    17 年前

    布莱恩,试试这样:

    import subprocess, sys
    
    def doit(cmd):
        #print cmd
        out = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True).stdout
        return out.read()
    

    因此,当按下按钮时,命令将使用子流程模块运行,您将以字符串形式获得输出。可以将其指定给文本控件的值以显示它。您可能需要输出.readfully()或多次读取才能逐步显示文本。

    wxPython demo 会告诉你该怎么做。

    推荐文章