Check if a process is running or not on Windows with Python
You can not rely on lock files in Linux or Windows. I would just bite the bullet and iterate through all the running programs. I really do not believe it will be as "expensive" as you think. psutil is an excellent cross-platform python module cable of enumerating all the running programs on a system.
import psutil "someProgram" in (p.name() for p in psutil.process_iter())
Although @zeller said it already here is an example how to use tasklist
. As I was just looking for vanilla python alternatives...
import subprocessdef process_exists(process_name): call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name # use buildin check_output right away output = subprocess.check_output(call).decode() # check in last line for process name last_line = output.strip().split('\r\n')[-1] # because Fail message could be translated return last_line.lower().startswith(process_name.lower())
and now you can do:
>>> process_exists('eclipse.exe')True>>> process_exists('AJKGVSJGSCSeclipse.exe')False
To avoid calling this multiple times and have an overview of all the processes this way you could do something like:
# get info dict about all running processesimport subprocessoutput = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()# get rid of extra " and split into linesoutput = output.replace('"', '').split('\r\n')keys = output[0].split(',')proc_list = [i.split(',') for i in output[1:] if i]# make dict with proc names as keys and dicts with the extra nfo as valuesproc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()): print('%s: %s' % (name, values))
win32ui.FindWindow(classname, None)
returns a window handle if any window with the given class name is found. It raises window32ui.error
otherwise.
import win32uidef WindowExists(classname): try: win32ui.FindWindow(classname, None) except win32ui.error: return False else: return Trueif WindowExists("DropboxTrayIcon"): print "Dropbox is running, sir."else: print "Dropbox is running..... not."
I found that the window class name for the Dropbox tray icon was DropboxTrayIcon using Autohotkey Window Spy.
See also