我想创建一个后台进程,用外部查看器
显示文件
。当进程停止时,它应该删除该文件。
下面的代码做了我想做的事情,但它很丑陋,我想有一种更惯用的方法。
如果它甚至独立于操作系统,那就完美了。
subprocess.Popen(viewer + ' ' + file + ' && rm ' + file, shell=True)
最佳答案
使用 subprocess.call()
打开查看器并查看文件就可以做到这一点。随后,运行命令删除该文件。
如果您希望脚本在进程运行时继续运行,请使用线程
一个例子:
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”。
关于python - popen完成后做一些事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39547820/