使用子流程关闭图像 [英] Close Image with subprocess
问题描述
我正在尝试通过子进程打开图像,以便用户可以看到它,然后关闭该图像以使其消失.
I am trying to open an image with subprocess so it is visible to the user, then close the image so that it disapears.
这个问题曾经被问过,但是我发现的答案对我没有用.这是我检查过的内容:
This question has been asked before, but the answers I found have not worked for me. Here is what I have checked:
杀死使用Python的subprocess.Popen()创建的进程
Killing a process created with Python's subprocess.Popen()
如何使用Python Imaging Library关闭显示给用户的图像?
我需要代码来打开图像(使用预览"(可选),在Mac上默认),请稍等片刻,然后关闭图像.
I need the code to open an image (with Preview (optional), default on my Mac), wait a second, then close the image.
openimg = subprocess.Popen(["open", mypath])
time.sleep(1)
openimg.terminate()
openimg.kill()
所有信息都告诉我终止()和终止(),但这仍然不能关闭图像.
Everything is telling me to terminate() and kill(), but that still isn't closing the image.
这不是必须使用预览,我也愿意听到其他选项.
This does not HAVE to use preview, I am open to hearing other options as well.
我还尝试了以下代码,但仍然没有成功
I have additionally tried the below code, still no success
print('openimg\'s pid = ',openimg.pid)
os.kill(openimg.pid, signal.SIGKILL)
推荐答案
我敢肯定,这是最骇人听闻的方法,但是它确实有效.如果有人偶然发现此问题,并且知道更好的方法,请告诉我.
I'm sure this is the hackiest way to do this, but hell, it works. If anyone stumbles on this and knows a better way, please let me know.
问题 正如 David Z 所述,我的目标不是正确的流程.因此,为了正确关闭它,我必须弄清楚正确的进程ID是什么.
The Problem As David Z described, I was not targeting the correct process. So I had to figure out what the correct process ID was in order to close it properly.
我首先打开终端并输入命令ps -A
.这将显示所有当前打开的进程及其ID.然后,我只搜索了Preview
,发现了两个打开的进程.
I started by opening my terminal and entering the command ps -A
. This will show all of the current open processes and their ID. Then I just searched for Preview
and found two open processes.
以前,我关闭了列表中的第一个Preview pid,我们称之为11329
,但列表中的第二个pid仍然打开.第二个预览过程11330
始终比第一个预览过程高1位.第二个是我要关闭Preview所需的pid.
Previously, I was closing the first Preview pid in the list, let's call it 11329
but the second on the list was still open. The second Preview process, 11330
, was always 1 digit higher then the first process. This second one was the pid I needed to target to close Preview.
答案
openimg = subprocess.Popen(["open", mypath]) ##Opens the image to view
newpid = openimg.pid + 1 ##Gets the pid 1 digit higher than the openimg pid.
os.kill(newpid, signal.SIGKILL) ##Kills the pid and closes Preview
这个答案似乎很脆弱,但是对我有用.我只是刚刚开始学习pid,所以如果有人可以提供一些知识,我将不胜感激.
This answer seems very fragile, but it works for me. I only just started learning about pids so if anyone could provide some knowledge, I would be grateful.
这篇关于使用子流程关闭图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!