Is there a way to check if a PID exists on Windows with Python without requiring libraries? How to?
Asked
Active
Viewed 4,687 times
4
-
by libraries you mean any (including python standard library) or just external ones? – Raven Jul 12 '13 at 17:41
-
By libraries I mean any relatively big piece of code I would have to include with my project or add to the list of dependencies (to install with `easy_install`, `pip` or whatever) – Alicia Jul 12 '13 at 17:56
-
possible duplicate of [Check if pid is not in use in Python](http://stackoverflow.com/questions/568271/check-if-pid-is-not-in-use-in-python) – moooeeeep Jul 12 '13 at 19:06
-
it could be as easy as `psutil.pid_exists(pid)` ... – moooeeeep Jul 12 '13 at 19:08
-
If psutil was in standard library. – Alicia Jul 12 '13 at 19:11
-
I just wanted you to wish for it. Otherwise I had put it as an answer. – moooeeeep Jul 12 '13 at 19:29
-
For a wish, I would prefer not to bear with Windows at all. – Alicia Jul 12 '13 at 20:05
-
Related: [How to detect if a process is running using Python on Win and MAC](http://stackoverflow.com/q/8135899/95735) – Piotr Dobrogost Jul 12 '13 at 21:48
2 Answers
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
-
-
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
-
4But won't work for anyone whose Windows is not set with English locale. – Alicia Jul 12 '13 at 19:15