4

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

Alicia
  • 1,132
  • 1
  • 14
  • 28

2 Answers2

4

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
Alicia
  • 1,132
  • 1
  • 14
  • 28
  • Could you specify OS version and architecture? – Alicia Mar 19 '14 at 20:51
  • Windows 8.1, x64. I think you need to check the exit result with a second API call AFTER the open process for this technique to work reliably on all versions of Windows. – Warren P Mar 20 '14 at 03:22
  • It seems it works as long as it's running with the same user as the checked process. – Alicia Mar 20 '14 at 09:52
  • Hm. I'm running from an elevated command prompt in win8.1, which then launches python, which then runs a subprocess, yet it doesn't work. – Warren P Mar 20 '14 at 14:21
  • If you are launching a subprocess, wouldn't it be more reliable to use `.poll()` instead? PIDs can be recycled. – Alicia Mar 20 '14 at 14:28
1

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
vidit
  • 6,293
  • 3
  • 32
  • 50