簡體   English   中英

wxpython GUI運行命令行程序

[英]wxpython GUI running a command-line program

我已經搜尋了一個小時,卻找不到確切的答案。

我正在嘗試編寫wxPython GUI應用程序,該應用程序具有一個按鈕,該按鈕可啟動命令行工具(全部在Windows上)。 該工具需要大約5分鍾的時間來運行,並隨其產生輸出。

我希望GUI具有某種文本窗口來顯示輸出。 我也想殺死GUI終止命令行過程。

我看過線程和Popen,似乎無法在它們之間建立正確的連接來完成這項工作。 誰能指出我一個明智的榜樣?

我寫了一篇文章,按照您所說的做事。 我需要運行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並讀取其stdout。 然后,在打印出來之前,我使用strip()命令從行的開頭和結尾刪除多余的空格。 當您執行打印時,它將被重定向到文本控件。

我在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM