在 popen 完成后做一些事情

Doing something after popen is finished

我想创建一个显示 file 和外部 viewer 的后台进程。当进程停止时,它应该删除该文件。 下面的一段代码做了我想做的,但它很丑,我想还有一种更惯用的方法。 如果它甚至是 OS 独立的,那将是完美的。

 subprocess.Popen(viewer + ' ' + file + ' && rm ' + file, shell=True)

使用subprocess.call() 打开查看器并查看文件即可。随后,运行删除文件的命令。

如果您希望脚本在进程 运行ning 期间继续,请使用 threading

一个例子:

from threading import Thread
import subprocess
import os

def test():
    file = "/path/to/somefile.jpg"
    subprocess.call(["eog", file])
    os.remove(file)

Thread(target = test).start()
# the print command runs, no matter if the process above is finished or not
print("Banana")

这将完全符合您的描述:

  • 使用 eog(查看器)打开文件,等待它完成(关闭eog)并删除文件。
  • 同时继续脚本并打印 "Banana"。