Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine in python if an external program is open?

Tags:

python

windows

I'm trying to determine in python if a certain application is already open so that I don't open it twice. I've done a little research and have found that it is possible to pull the process name of a program, but the only issue I have with that is the program I am checking for itself has a pretty generic process name (in this case, "pythonw.exe" or "cmd.exe").

It does however have differing names in the application list of Windows Task Manager, so my question is if there is any way to use that to detect if a program is open or not. My workplace will not allow me to download additional programs or modules to use for this script, so the answer needs to use the os module or something similar that is already included in the windows library.

like image 666
Christian Boler Avatar asked Jan 15 '23 14:01

Christian Boler


1 Answers

I use the following code to check if a certain program is running:

import psutil     #psutil - https://github.com/giampaolo/psutil

# Get a list of all running processes
list = psutil.pids()

# Go though list and check each processes executeable name for 'putty.exe'
for i in range(0, len(list)):
    try:
        p = psutil.Process(list[i])
        if p.cmdline()[0].find("putty.exe") != -1:
            # PuTTY found. Kill it
            p.kill()
            break;
    except:
        pass

PS: You can install your own modules using Virtual ENV or just choose an alternative installation path!

like image 144
Nippey Avatar answered Jan 21 '23 16:01

Nippey