2009-05-18 89 views
1

我正在尋找相當於我的回答Tcl/Tk examples?的wxPython。具體來說,我想看一個如何創建幾個按鈕的例子,每個按鈕在點擊時運行一些外部命令。在進程運行時,我希望輸出轉到可滾動的wxPython小部件。wxPython:異步執行命令,在文本部件中顯示stdout

當進程運行時,GUI不應該被阻塞。例如,假設其中一個按鈕可以啓動開發任務,如構建或運行單元測試。一個按鈕被點擊時

回答

5

在這裏,一個完整的工作示例。

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() 
0

啓動一個線程:

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

使用wx.PostEvent和wx.lib.newevent從回調將消息發送到主線程。

This link may be helpful。

+0

我很感謝您的建議,但我正在尋找一個使用wxPython的具體示例。假設我對wxPython一無所知,並且你會非常接近真相。 – 2009-05-18 20:15:39

0

布萊恩,嘗試這樣的事情:

import subprocess, sys 

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

所以按下按鈕時,該命令被使用的子模塊運行,你得到的輸出作爲一個字符串。您可以將其分配給文本控件的值以顯示它。您可能不得不out.readfully()或多次閱讀以逐步顯示文本。

如果按鈕&的文本字段不熟悉,那麼快速瀏覽一下wxPython demo會告訴你該怎麼做。

+0

這不符合我的標準之一:「在運行過程中GUI不應該阻止」。在你的例子中,當你等待out.read()完成時,UI會被阻塞。 – 2009-06-24 01:00:07

+0

是什麼讓你說Bryan?你試過了嗎?我的理解是你可以通過執行Popen.wait()來阻止它,但是如果你不用阻塞wait命令,你將能夠通過read命令讀取當時可用的任何stdout。 http://docs.python.org/library/subprocess.html – 2009-06-24 11:38:28

相關問題