Search code examples
pythonlinuxmacossubprocesskill-process

How to terminate application opened by python subprocess


I am trying to open a pdf file with the default application on macos, which is preview, with

import subprocess
doc = subprocess.Popen(['open', 'path_to_doc.pdf'])

and close it.

I have tried the solutions in How to terminate a python subprocess launched with shell=True but none of them works.

process = psutil.Process(doc.pid)

results in psutil.Process(pid=6994, name='open', status='zombie', started='12:07:11'). process.children(recursive=True) is empty.

os.getpgid(doc.pid) results in ProcessLookupError: [Error 3]No such process. By checking Activity Monitor (An application to view processes), I find the pid of the application is always doc.pid+1. In case doc.pid == 6994, the pid of the application is 6995. I can close the app with os.killpg(doc.pid+1, signal.SIGTERM), but this seems subjective that might not always work.

I am aware of osascript on macos to close applications such as with the code

clo = subprocess.Popen(['osascript', '-e', '''quit app "preview"'''])

However I would like a solution across platforms.


Solution

  • you could resort to lsof ..., a trivial example below ... , then use logic to determine if a given entry matches criteria (username,filename etc ) ....

    consult lsof documentation for intricacies .

    lsof -FuncL n/Users/ticktalk/Downloads/w_aaaa1364.pdf
    p87598
    cPreview
    u501
    Lticktalk
    ftxt
    n/Users/ticktalk/Downloads/w_aaaa1364.pdf