Eugene S
Eugene S

Reputation: 6910

Check if process is running in Windows using only Python built-in modules

I know that there are a couple of ways to complete that task using psutil or win32ui modules. But I wonder if there's an option to do that using Python built-in modules only? I have also found this question:

Check if PID exists on Windows with Python without requiring libraries

But in this case the object is located by PID and I want to do it using process name.

Upvotes: 3

Views: 15418

Answers (3)

Memetics
Memetics

Reputation: 1

If all you're trying to do is test whether a process is running by its process name, you could just import the check_output method from the subprocess module (not the entire module):

from subprocess import check_output

print('Test whether a named process appears in the task list.\n')
processname = input('Enter process name: ')   # or just assign a specific process name to the processname variable 
tasks = check_output('tasklist')
if processname in str(tasks):
    print('{} is in the task list.'.format(processname))
else:
    print('{} not found.'.format(processname))

Output:

>>> Discord.exe
Discord.exe is in the task list.

>>> NotARealProcess.exe
NotARealProcess.exe not found.

(This works for me on Windows 10 using Python 3.10.) Note that since this is just searching for a specific string across the entire task list output, it will give false positives on partial process names (such as "app.exe" or "app" if "myapp.exe" is running) and other non-process text input that happens to be in the task list:

>>> cord.ex
cord.ex is in the task list.

>>> PID Session Name
PID Session Name is in the task list.

This code generally should work fine if you just want to find a known process name in the task list and are searching by the whole name, but for more rigorous uses, you might want to use a more complex approach like parsing the task list into a dictionary and separating out the names for more focused searching, as well as add some error checking to handle edge cases.

Upvotes: 0

Lexx Tesla
Lexx Tesla

Reputation: 151

Maybe this will help you:

import subprocess

s = subprocess.check_output('tasklist', shell=True)
if "cmd.exe" in s:
    print s

Upvotes: 6

Mike Driscoll
Mike Driscoll

Reputation: 33111

Without PyWin32, you're going to have to go at it the hard way and use Python's ctypes module. Fortunately, there is already a post about this here on StackOverflow:

You might also find this article useful for getting a list of the running processes:

Upvotes: 1

Related Questions