How to determine the running process based on its PID in python on Windows?

I have a python script that starts the application and grabs the PID and waits until this process ID is no longer found using:

result = subprocess.Popen( r'tasklist /fi "PID eq ' + str(PID) + '"', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 

This works fine for me until I try to run it on XP Home, which of course does not have tasklist.exe

Is there another way to determine if a process is running or not, given the PID of the process.

Just starting the process using subprocess.Popen and waiting for it to finish is NOT an option, since the process must be disconnected, since I need to perform other tasks while the initial process is running.

Any thoughts?

+4
source share
2 answers

If you are not opposed to installing Python Win32 extensions , you can use the Windows API to wait for the process to complete:

 from win32con import SYNCHRONIZE from win32event import WaitForSingleObject, INFINITE from win32api import OpenProcess, CloseHandle process_handle = OpenProcess(SYNCHRONIZE, False, pid) try: WaitForSingleObject(process_handle, INFINITE) finally: CloseHandle(process_handle) 

This will block the code until the process ends (the INFINITE value in the WaitForSingleObject() value can be changed if desired, see the documentation ).


Alternatively, without installing the extension, you can do this with ctypes , especially easily, since all the necessary methods are located in kernel32.dll :

 from ctypes import windll SYNCHRONIZE = 0x100000L INFINITE = 0xFFFFFFFFL process_handle = windll.kernel32.OpenProcess(SYNCHRONIZE, 1, pid) windll.kernel32.WaitForSingleObject(process_handle, INFINITE) windll.kernel32.CloseHandle(process_handle) 

Of course, in this case the error handling code (omitted) is a bit more complicated and much smaller than Pythonic.

+2
source

You can try using WMIC. I think it is available in XP Home. Here is the command:

 wmic process get description,executablepath,processid 
0
source

All Articles