Close Image with subprocess

后端 未结 2 1213
独厮守ぢ
独厮守ぢ 2021-01-17 01:02

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 an

2条回答
  •  遥遥无期
    2021-01-17 01:56

    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.

    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.

    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.

    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.

    The Answer

    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
    

    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.

提交回复
热议问题