Dan
Dan

Reputation: 1

What is the best way to see if a python process is already running?

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.

Upvotes: 0

Views: 424

Answers (3)

Jérôme
Jérôme

Reputation: 14704

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"`

Upvotes: 3

justengel
justengel

Reputation: 6320

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.")

Upvotes: -1

Malik Brahimi
Malik Brahimi

Reputation: 16711

There are Linux commands that return a list of processes:

if 'your_process' in commands.getoutput('ps -A'):
    print 'Your process in running.'

Upvotes: 2

Related Questions