How to check if a process with Command line argument is running using python


I would like to check if a script is running with a specific command line argument within a python script.

For example I would like to check if: testarg

Is running. Is there any way I can achieve this?

Thanks in advance

Asked By: Daniel Pilch



To search through the currently running processes, you should use a library such as psutil to ensure maximum platform compatibility.

import psutil

for process in psutil.process_iter():
    cmdline = process.cmdline()
    if "" in cmdline and "testarg" in cmdline:
        # do something

If instead you are looking to search through the arguments of the current process you can use the sys.argv list:

import sys

if "testarg" in sys.argv:
    # do something

For more complex argument parsing, it is recommended to use argparse.

Answered By: Tom Leese

You can use the psutil library.

import psutil

process_is_running = False

for process in psutil.process_iter():
    if process.cmdline == what_you_want:
        process_is_running = True

This will work on almost any OS and with python 2.4 up to 3.3.

Answered By: Bakuriu

Here is my take of it:

import psutil

L=[(,p.cmdline()[1]) for p in psutil.process_iter() if'py')]

Now if you print this list L out:

('py.exe', 'programs\')
('python.exe', 'programs\')
('python.exe', '-u')
('python.exe', 'programs\')

The list contains the command line parameters of every running process whose name starts with ‘py’. That would include python.exe and py.exe. The condition is necessary otherwise you may run into some AccessDenied error if you try to poke on every running Windows process, like some smss.exe.
Once you have this list, finding out what you want is a no brainer:

t=['what_you_want' == m[1] for m in L]
answer=True in t
Answered By: user3103059

This helped me when I wanted to match specific process with specific arguments :

import psutil
for proc in psutil.process_iter():
    if ('ruby')) and ("service-buffer.rb" in proc.cmdline()[1]) :
        print("match", proc.cmdline()[1])
Answered By: Tomas Pytel
import psutil

for p in psutil.process_iter():
    try:   # else get PermissionError
        pid     =
        cmdline = p.cmdline()
        for cmd in cmdline:
Answered By: Bill Qualls
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.