Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 976
imp Avatar asked Oct 17 '25 17:10

imp


2 Answers

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

# Python2
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.

# Python3
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.

like image 110
salmanwahed Avatar answered Oct 19 '25 06:10

salmanwahed


Use module psutil. For example:

import psutil

# ...    

if pid in psutil.get_pid_list():
    print(pid, "is running")

Edit: You can get pids and names of all running processes like this:

for p in psutil.process_iter():
    if p.name == 'firefox':
        print("firefox is running")
        break
like image 37
Jan Bednařík Avatar answered Oct 19 '25 07:10

Jan Bednařík



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!