4

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

Community
  • 1
  • 1
imp
  • 1,967
  • 2
  • 28
  • 40

3 Answers3

7

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.

JayRizzo
  • 3,234
  • 3
  • 33
  • 49
salmanwahed
  • 9,450
  • 7
  • 32
  • 55
  • Yes. in python3x we can not use this module. we can use `subprocess` module instead. – salmanwahed Apr 10 '14 at 10:56
  • This is one approach of solving this. But I did not get what you meant by pure Python. Thanks. – salmanwahed Apr 10 '14 at 15:47
  • although this pgrep based answer is the only viable one for me, and it works - still 'pgrep' is a command line tool not always available, and is NOT part of python. It is a bit weird that nothing within Python standard libraries (even in the "subprocess" module) can help you find the pid of some process by name. Beyond this, it is also important to state that there may by SEVERAL processes with the same name, and that you need to apply some logic to pgrep results, or at least run it with -n ('pgrep -n firefox') to limit it to the newest process with that name. – Motti Shneor Jun 23 '16 at 08:00
4

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
JayRizzo
  • 3,234
  • 3
  • 33
  • 49
1

I was just trying the above code and it did not work for me using python 2.7 Haven't tried the code on python 3. Posting the updated code, it might help someone

for p in psutil.process_iter():  # iterate through all running processes 
    if p.name() == 'firefox':
        print("firefox is running")
        break
JayRizzo
  • 3,234
  • 3
  • 33
  • 49
Ritesh Karwa
  • 2,196
  • 1
  • 13
  • 17