How to check in Mac OSX with Python if a process is RUNNING or not

imp picture imp · Apr 10, 2014 · Viewed 7.9k times · Source

I am using python 2.7 on mac osx 10.9.

I want to check whether, a process is running or not. I looked into this Q&A, but result is not desired.

I want to check, whether any process of a particular name is running or not

Answer

salmanwahed picture salmanwahed · Apr 10, 2014

Try this. If it returns a process id then you have the process running. Use your process name instead of firefox.

import commands
commands.getoutput('pgrep firefox')

As commands module is no longer in python 3x, We can receive the process id using subprocess module here.

import subprocess
process = subprocess.Popen('pgrep firefox', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
my_pid, err = process.communicate()

Here my_pid will be process id.