2015-07-10 97 views
0

我通過ssh有一個長時間運行任務的應用程序,它獲取stdout然後打印到wx.TextCtrl,這一切工作正常。我現在的問題是能夠退出應用程序,目前當我執行gui掛起時。長時間的sunning ssh任務應該繼續在遠程服務器上運行,我只想關閉應用程序。如何正確地打破while True循環以及按下退出按鈕時的ssh任務?關閉wxpython應用程序掛起gui

import wx 
import wx.stc as stc 
from subprocess import Popen, PIPE, STDOUT 
import sys 
import spur 
import threading 
import select 
import codecs 
import os 
import time 
import io 

class MainWindow(wx.Frame): 
    def __init__(self, parent, id, title): 
     wx.Frame.__init__(self, parent, id, title, size=(600, 500), style=wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | 
               wx.RESIZE_BOX | 
               wx.MAXIMIZE_BOX)) 

     self.running_log = wx.TextCtrl(self, pos=(5, 5), size=(570,390)) 

     self.buttonGo = wx.Button(self, -1, "Go", pos=(180,420)) 
     self.buttonGo.Bind(wx.EVT_BUTTON, self.Go) 
     self.buttonClose = wx.Button(self, -1, "Quit", pos=(285,420)) 
     self.buttonClose.Bind(wx.EVT_BUTTON, self.OnClose) 
     self.Show() 

     self.CreateStatusBar() 
     menuBar = wx.MenuBar() 
     menu = wx.Menu() 
     self.SetMenuBar(menuBar) 
     self.sshLog1 = sshLog(self) 
     self.Centre() 
     self.Show() 

    def Go(self, event): 
     threading.Thread(target=self.sshLog1.runCommand).start()   
     threading.Thread(target=self.sshLog1.readlog1).start() 

    def OnClose(self, e): 
     sys.exit() 
     CloseApp() 

class sshLog(wx.Panel): 
    def __init__(self, parent): 
     wx.Panel.__init__(self, parent) 
     self.parent = parent 
     self.frame = self 

    def runCommand(self): 
     self.output_file = io.BytesIO() 
     shell = spur.SshShell(hostname='10.0.1.1', username='remoteUsername', password='remotePassword', missing_host_key=spur.ssh.MissingHostKey.accept) 
     process = shell.spawn(['ping', 'google.com', '-t'], stdout=self.output_file) 
     process.wait_for_result() 

    def readlog1(self): 
     while True: 
      time.sleep(1) 
      wx.CallAfter(self.readlog2) 

    def readlog2(self): 
     last_line = str(self.output_file.getvalue()) 
     wx.CallAfter(self.parent.running_log.AppendText, last_line) 

############################### 
########## CLOSE APP ########## 
############################### 
class CloseApp(wx.Frame): 
    def __init__(e): 
     sys.exit(0) 

app = wx.App() 
MainWindow(None, -1, 'My App') 
app.MainLoop() 

回答

0

這被張貼到我的wxPython的用戶羣:

你不能打破「而真正的」循環。您必須提供循環退出的方式: while self.LoopContinue: 然後,當您希望線程死掉時,將self.sshLog1.LoopContinue設置爲false。

但是,這不會結束在「process.wait_for_result()」中阻塞的另一個線程。如果你想讓它變成可中斷的,你也必須把它變成一個循環。但是,由於流程退出後您沒有做任何事情,您爲何等待它退出?只需生成過程並立即返回。

- 蒂姆·羅伯茨,TI ... @ probo.com Providenza & BOEKELHEIDE公司