0

I'm trying to write a script that monitors my python program to see if it is already running.

I started by trying to assign this script to an object:

processWatch = os.system("sudo ps afxj | grep quickConversion.py")
if processWatch > 2:  #if more than one is running it won't run.
    while 1:
        "rest of loop"

I then tried to monitor the object for more than one instance.

horns
  • 1,843
  • 1
  • 19
  • 26
Dan
  • 1
  • 1

3 Answers3

3

You may want to pay a look at psutils to handle processes.

import psutil

processWatch = [p.cmdline() for p in psutil.process_iter()].count(['python', 'quickConversion.py'])
if processWatch > 0:
    `while 1: `
        `"rest of loop"`
Jérôme
  • 13,328
  • 7
  • 56
  • 106
2

There are Linux commands that return a list of processes:

if 'your_process' in commands.getoutput('ps -A'):
    print 'Your process in running.'
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • I'm trying to make the program somewhat "Self-aware" so that if it sees an instance of itself already running it won't run again. I'm using crontabs to run the program every minute so that if it fails it will restart. What could I do to ensure the program won't run if it is already running? – Dan Mar 27 '15 at 14:27
-1

Subprocess's Popen is very useful for this. https://docs.python.org/3.4/library/subprocess.html

import subprocess

process = subprocess.Popen(cmd)
if process.poll() is None:
    print("The process hasn't terminated yet.")
justengel
  • 6,132
  • 4
  • 26
  • 42
  • I could be wrong, but I don't think the OP is talking about processes launched by Python (for which you could use subprocess). – Steven Rumbalski Mar 27 '15 at 14:32
  • I'm trying to nest this script within the program that it is monitoring so that when I run the program it will monitor itself at the same time. Can Popen monitor running python programs? – Dan Mar 27 '15 at 14:32
  • @Dan: Are you running one instance of your program or multiple instances? How are they launched? By Python or by running them independently? – Steven Rumbalski Mar 27 '15 at 14:36
  • I am running one instance. I'm using crontab to run the program so that if it fails it will restart. They are launched by crontab. – Dan Mar 27 '15 at 14:45