Daniel Pilch
Daniel Pilch

Reputation: 2247

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:

main.py testarg

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

Thanks in advance

Upvotes: 8

Views: 14255

Answers (5)

Tom Leese
Tom Leese

Reputation: 19699

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 "main.py" 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.

Upvotes: 17

Bill Qualls
Bill Qualls

Reputation: 407

import psutil

for p in psutil.process_iter():
    try:   # else get PermissionError
        pid     = p.pid
        cmdline = p.cmdline()
        print(pid)
        for cmd in cmdline:
            print(cmd)
        print()
    except:
        pass

Upvotes: 1

Tomas Pytel
Tomas Pytel

Reputation: 188

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

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

Upvotes: 1

user3103059
user3103059

Reputation:

Here is my take of it:

import psutil

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

Now if you print this list L out:

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

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

Upvotes: 2

Bakuriu
Bakuriu

Reputation: 101929

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.

Upvotes: 6

Related Questions