Alicia
Alicia

Reputation: 1161

Check if PID exists on Windows with Python without requiring libraries

Is there a way to check if a PID exists on Windows with Python without requiring libraries? How to?

Upvotes: 4

Views: 4793

Answers (2)

Alicia
Alicia

Reputation: 1161

This is solved with a little cup of WINAPI.

def pid_running(pid):
    import ctypes
    kernel32 = ctypes.windll.kernel32
    SYNCHRONIZE = 0x100000

    process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
    if process != 0:
        kernel32.CloseHandle(process)
        return True
    else:
        return False

Upvotes: 4

vidit
vidit

Reputation: 6461

This works on my system..

>>> import subprocess
>>> out = subprocess.check_output(["tasklist","/fi","PID eq 1234"]).strip()
>>> if out == "INFO: No tasks are running which match the specified criteria.":
...   print "No such PID :D"
...
No such PID :D

Upvotes: 1

Related Questions