我有一个小的 python 脚本,我通过将图像写入临时文件来显示图像,在临时文件上调用 eog,然后在 eog 进程关闭后在临时文件上调用 rm。相关代码基本上是这样的:
os.popen('(eog --new-instance tmp.jpg; rm tmp.jpg)&')
--new-instance 标志很重要;如果没有它,如果已经有一个 eog 进程,eog 调用只是告诉预先存在的 eog 进程显示 tmp.jpg 并立即返回。 rm 在预先存在的 eog 进程可以打开 tmp.jpg 之前执行。预先存在的 eog 进程然后崩溃。
不幸的是,我无法完全控制使用此脚本的某些系统。其中一些安装了不支持 --new-instance 的过时版本的 eog,我不想耗尽构建本地副本的配额空间。
有什么方法可以启动 eog 以防止它检测是否有其他实例?或者是否有另一种可靠的策略可以在复杂的查看器中显示图像(即,支持缩放、平移等),不会让临时文件弄乱我的目录?
请您参考如下方法:
eog 按名称监控文件,因此您不能只是打开图像然后安全地取消链接。
您可以在删除文件之前引入延迟:
#!/usr/bin/env python
import os
import subprocess
import tempfile
import time
from threading import Thread
def write_image_to(f):
f.write(open(os.path.expanduser('~/Pictures/lenaNN.jpg'), 'rb').read())
def f(write_image_to, delay=None):
with tempfile.NamedTemporaryFile() as fileobj:
write_image_to(fileobj)
fileobj.flush() # ensure writing to disk
r = subprocess.call(['eog','--new-instance',fileobj.name],close_fds=True)
if r: # eog don't support new-instance
subprocess.call(['eog', fileobj.name], close_fds=True)
if delay:
time.sleep(delay)
for _ in xrange(10):
Thread(target=f, args=(write_image_to, 3600)).start()
为避免等待延迟到期,您可以在后台调用脚本:
$ python your_script.py & disown
disown 确保脚本在您注销后继续工作。
