在windows python中传递命令后继续

2024-04-25 08:41:39 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我正在使用的函数。当我调用spawnaputty会话命令时,它会完全冻结我的gui程序,直到我关闭putty会话。有没有办法绕过这个问题,让它调用命令,然后继续前进?(我传给司令部的还有更多,但我已经把它移走了,要把它清理干净。你知道吗

def SpawnSessionrmt(self,event):
    if "SSH" in self.protormt:
        subprocess.call('C:/bin/putty.exe ',shell=True)
    elif "RDP" in self.protormt:
        subprocess.call('C:/bin/rdp.exe)
    else:
        print "Not that you will see this...but that isn't a valid protocol"

Tags: 函数in命令self程序binthatgui
1条回答
网友
1楼 · 发布于 2024-04-25 08:41:39

问题是,正如the docs所说,call将:

Run the command described by args. Wait for command to complete, then return the returncode attribute.

如果不想等待命令完成,请不要使用call。只需创建一个Popen实例(理想情况下,稍后为它创建wait,可能在退出时,或者在后台线程中)。你知道吗

例如:

def SpawnSessionrmt(self,event):
    if "SSH" in self.protormt:
        self.children.append(subprocess.Popen('C:/bin/putty.exe ',shell=True))
    elif "RDP" in self.protormt:
        self.children.append(subprocess.Popen('C:/bin/rdp.exe'))
    else:
        print "Not that you will see this...but that isn't a valid protocol"

def WaitForChildren(self):
    for child in self.children:
        child.wait()

对于GUI应用程序,我认为最简单的方法可能是将subprocess.call放入后台线程。这样,您就可以在实际工作完成时更新GUI。你知道吗

不幸的是,每个GUI框架都有不同的实现方式,有些允许您从任何线程执行GUI操作,有些具有run_on_main_thread功能,有些允许您将事件发布到主线程以由其事件循环拾取,有些要求您构建自己的线程间通信系统,等等,你没有告诉我们你在用哪个GUI框架。你知道吗

下面是一个我随机挑选的框架的例子wx

def SpawnSessionrmt(self,event):
    if "SSH" in self.protormt:
        cmd = 'C:/bin/putty.exe'
    elif "RDP" in self.protormt:
        cmd = 'C:/bin/rdp.exe'
    else:
        print "Not that you will see this...but that isn't a valid protocol" 
        return
    def background_function():
        result = subprocess.call(cmd)
        event = wx.CommandEvent(MY_UPDATE_ID)
        event.SetInt(result)
        self.GetEventHandler().AddPendingEvent(event)
    t = threading.Thread(target=background_function)   
    t.daemon = True
    t.start()

(另外,我讨厌我的随机数生成器,因为我讨厌wx…但至少它没有选择Tkinter,这会迫使我围绕QueueCondition编写自己的跨线程通信。)

相关问题 更多 >

    热门问题