Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 657
Daniel Pilch Avatar asked Dec 21 '13 17:12

Daniel Pilch


People also ask

How do you check if a process is already running in Python?

Answer #1: Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up.


1 Answers

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

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.

like image 143
Tom Leese Avatar answered Sep 23 '22 06:09

Tom Leese