【问题标题】:How check if a process has finished but without waiting?如何检查进程是否已完成但无需等待?
【发布时间】:2021-11-15 15:25:14
【问题描述】:

我正在 python/tkinter 中做一个小项目,我一直在寻找一种方法来检查进程是否已完成但“无需等待”。我试过了:

process = subprocess.Popen(command)
while process.poll() is None:
    print('Running!')
print('Finished!')

或:

process = subprocess.Popen(command)
stdoutdata, stderrdata = process.communicate()
print('Finished!')

两个代码都执行命令并打印“完成!”当进程结束时,但主程序冻结(等待),这就是我想要避免的。 我需要 GUI 在进程运行时保持功能,然后在它完成后立即运行一些代码。有什么帮助吗?

【问题讨论】:

  • 你可以创建一个线程来等待。

标签: python tkinter process subprocess wait


【解决方案1】:

您通常会为此目的使用 Thread 模块:

例如:

# import Thread
from threading import Thread
import time

# create a function that checks if the process has finished
process = True
def check():
    while process:
        print('Running')
        time.sleep(1) # here you can wait as much as you want without freezing the program
    else:
        print('Finished')

# call the function with the use of Thread
Thread(target=check).start()
# or if you want to keep a reference to it
t = Thread(target=check)
# you might also want to set thread daemon to True so as the Thread ends when the program closes
t.deamon = True
t.start()

这样,当您执行process=False 时,程序将结束并且输出将显示'Finished'

【讨论】:

  • 但是我需要运行一个外部命令。如何使用 subprocess.Popen 来实现这一点?该命令需要很长时间才能完成。
  • 您可以尝试在线程中运行的函数中运行您想要的任何命令。例如在上面的checker 函数中添加执行外部命令的代码
猜你喜欢
  • 1970-01-01
  • 2021-07-28
  • 2017-05-20
  • 2021-07-13
  • 2021-11-08
  • 2017-11-13
  • 2012-03-16
  • 2010-11-06
相关资源
最近更新 更多