0

我这个应用程序通过 ssh 有一个长时间运行的任务,stdout然后将它打印到 a wx.TextCtrl,这一切都很好。我遇到的问题是能够退出应用程序,目前当我执行 gui 时会挂起。长时间的 sunning ssh 任务应该继续在远程服务器上运行,我只想关闭应用程序。按下退出按钮时,如何正确中断while True循环以及 ssh 任务?

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

1 回答 1

0

这是在 wxPython-users 组上发布给我的:

你不能打破“while True”循环。您必须提供一种退出循环的方法: while self.LoopContinue: 然后,当您希望线程终止时,将 self.sshLog1.LoopContinue 设置为 false。

但是,这不会结束在“process.wait_for_result()”中阻塞的另一个线程。如果您希望它是可中断的,您也必须将其更改为循环。但是,既然进程退出后你什么都不做,你为什么要等它退出呢?只需生成该进程并立即返回。

— Tim Roberts, ti...@probo.com Providenza & Boekelheide, Inc.

于 2015-07-12T13:05:32.037 回答