python - popen完成后做一些事情

标签 python python-3.x subprocess popen

我想创建一个后台进程,用外部查看器显示文件。当进程停止时,它应该删除该文件。 下面的代码做了我想做的事情,但它很丑陋,我想有一种更惯用的方法。 如果它甚至独立于操作系统,那就完美了。

 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/

相关文章:

java - Python 中的多重继承;如何在 Java 中这样做?

python - django 计算中的 0.01 differecene

python - 子进程模块 : using the call method with tempfile objects

python - 子进程中未收到 Popen send_signal 信号

python - 获取子类名称?

Python 的 SQLAlchemy 不会清除辅助(多对多)表?

python-3.x - 零精度训练Keras中的神经网络

python - 为什么 bool 比较中的赋值会输出这样的结果?

python - 在单独的进程组挂起中运行 Fabric 命令

python - 如何防止企业客户端混淆我的代码?