如何在不锁定GUI的情况下知道进程是否结束?

时间:2013-04-19 13:49:42

标签: python tkinter subprocess

我正在创建一个用C语言运行程序的python接口,我需要知道这个C程序是否成功结束,但是我知道这样做的唯一方法是在C程序未完成时锁定接口。有没有人知道如何在不阻止界面的情况下做到这一点?

以下是代码段:

def runProg(self):
    """This funcion will run the simulation"""

    if self.openned.get() ==  1:
        self.pid = StringVar()
        a = open(self.nameFile.get(),"w")
        self.writeFile()

        self.process = subprocess.Popen([self.cmdSys.get()+self.dV.get()+
                                         self.extension.get(),self.nameFile.get()])
        self.pid = self.process.pid

        #isso trava a interface para processos muito grandes até que o mesmo tenha    terminado
        if self.process.wait() == 0:
            tkMessageBox.showinfo("","Your simulation was completed sucessfully.")

3 个答案:

答案 0 :(得分:1)

self.process.wait()调用将阻塞,直到子进程结束,但是,正如您所发现的,如果您在主GUI线程中调用它,它将阻止您的GUI处理任何更多事件,直到该事件发生。< / p>

相反,您只需检查它是否以self.process.poll()结束,如果进程仍在运行,它将立即返回None

但是,如果你想要在完成后发生某些事情,你将不得不设置某种定时事件来监视子进程。

另一种选择是在后台线程中启动子进程,并使用阻塞wait()方法。有关详细信息,请参阅this question

答案 1 :(得分:0)

来自子流程模块documentation

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

运行args描述的命令。等待命令完成,然后返回returncode属性。

subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

使用参数运行命令。等待命令完成。如果返回码为零则返回,否则引发CalledProcessError。 CalledProcessError对象将在returncode属性中包含返回代码。

所以我会使用subprocess.call()的{​​{1}}或subprocess.check_call()函数intead。

答案 2 :(得分:0)

子进程Popen类有一个returncode属性,根据pydoc:

  

无值表示该过程   尚未终止。负值-N表示   child被信号N终止(仅限UNIX)。