如何检查进程是否已完成但无需等待?

How check if a process has finished but without waiting?

我在 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 在进程 运行 期间保持正常运行,然后 运行 在它完成后立即编写一些代码 。有帮助吗?

您通常为此目的使用 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'