1

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')
zero
  • 41
  • 4
  • If the user already killed it, there is no need for you to do anything more. I don't think you need `psutil` here, you can just [`poll()`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen.poll) to check whether the process object is alive. Probably add a small sleep so you don't do this thousands of times per second. – tripleee May 13 '22 at 12:39
  • Or simply use `subprocess.run()` instead and just wait for it to exit, if your Python code has nothing useful to do in the meantime. – tripleee May 13 '22 at 12:41
  • The propurse here is to get the actual process opened. I dont uderstant well why the process spawn by Popen() is killed even the application still running. In this case, i opened the calculator and the subprocess is gone (after poll() returns 0). But the application Calculator.exe still running on the SO. I want to take this actual process. – zero May 13 '22 at 17:19

1 Answers1

0

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')