簡體   English   中英

關閉wxpython應用程序掛起gui

[英]Closing wxpython application hangs gui

在這個應用程序中,它通過ssh執行了長期運行的任務,該應用程序獲取stdout然后將其打印到wx.TextCtrl ,所有這些都可以正常工作。 我遇到的問題是能夠退出應用程序,當前在執行gui掛起時。 長時間運行的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()

這是在wxPython-users組上發布給我的:

您不能中斷“ while True”循環。 您必須提供一種退出循環的方法:while self.LoopContinue:然后,當您希望線程死亡時,請將self.sshLog1.LoopContinue設置為false。

但是,這不會結束另一個線程,該線程正在“ process.wait_for_result()”中阻塞。 如果您希望它是可中斷的,則還必須將其更改為循環。 但是,由於您在進程退出后實際上並沒有做任何事情,為什么還要等待它退出呢? 只需生成該過程並立即返回即可。

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

暫無
暫無

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

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