'How keep tracking the external program opened in python?

I want open a program (ex: calculator) and keep tracking his process as the pid, name, etc. But, after calling the subprocess.Popen(), the process id is killed after few time.

So i want to initialize this program and get the process id and other informations and kill the process only if the user close the application (in this case, the calculator).

import subprocess
import psutil

process = subprocess.Popen('C:\Windows\System32\calc')

while psutil.pid_exists(process.pid):
    print('Process running')
print('Done')


Solution 1:[1]

Please note that I only got Mac right now so the code runs correctly on it. However, I think it will function properly on Windows as well if you insert the file path of the application correctly.

For Windows

import subprocess 
import psutil 
import time

print(psutil.__version__) # tested on 5.9.0

process = subprocess.Popen('C:\Windows\System32\calc')

# wait a moment to make sure that the app is open 
time.sleep(1)

is_running = True

while is_running:
    # check if the app is running
    is_running = "calc" in (p.name() for p in psutil.process_iter())
    print('Process running')

print('Done')

For MAC

import subprocess
import psutil
import time

print(psutil.__version__) # tested on 5.9.0

process = subprocess.Popen(['open', '/System/Applications/Calculator.app'])

# wait a moment to make sure that the app is open
time.sleep(1)
is_running = True

while is_running:
    # check if the app is running
    is_running = "Calculator" in (p.name() for p in psutil.process_iter())
    print('Process running')

print('Done')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1