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
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With