Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a process is running using Python on Win and MAC

Tags:

python

process

I am trying to find out a way to detect if a process is running in Windows Task Manager for Windows OS and Macintosh Activity Monitor for MAC OS using Python

Can someone please help me out with the code please?

like image 779
Pankaj Vatsa Avatar asked Nov 15 '11 11:11

Pankaj Vatsa


People also ask

How do you check if a process is running using Python?

To check if process is running or not, let's iterate over all the running process using psutil. process_iter() and match the process name i.e. Check if there is any running process that contains the given name processName.

How can I tell if Python script is running on Windows?

You can use psutil. Process().

How do I find the process ID in Python?

We can get the pid for the current process via the os. getpid() function. We may also get the pid for the parent process via the os. getppid() function.


2 Answers

psutil is a cross-platform library that retrieves information about running processes and system utilization.

import psutil

pythons_psutil = []
for p in psutil.process_iter():
    try:
        if p.name() == 'python.exe':
            pythons_psutil.append(p)
    except psutil.Error:
        pass
>>> pythons_psutil
[<psutil.Process(pid=16988, name='python.exe') at 25793424>]

>>> print(*sorted(pythons_psutil[0].as_dict()), sep='\n')
cmdline
connections
cpu_affinity
cpu_percent
cpu_times
create_time
cwd
exe
io_counters
ionice
memory_info
memory_info_ex
memory_maps
memory_percent
name
nice
num_ctx_switches
num_handles
num_threads
open_files
pid
ppid
status
threads
username

>>> pythons_psutil[0].memory_info()
pmem(rss=12304384, vms=8912896)

In a stock Windows Python you can use subprocess and csv to parse the output of tasklist.exe:

import subprocess
import csv

p_tasklist = subprocess.Popen('tasklist.exe /fo csv',
                              stdout=subprocess.PIPE,
                              universal_newlines=True)

pythons_tasklist = []
for p in csv.DictReader(p_tasklist.stdout):
    if p['Image Name'] == 'python.exe':
        pythons_tasklist.append(p)
>>> print(*sorted(pythons_tasklist[0]), sep='\n')
Image Name
Mem Usage
PID
Session Name
Session#

>>> pythons_tasklist[0]['Mem Usage']
'11,876 K'
like image 72
Eryk Sun Avatar answered Oct 05 '22 23:10

Eryk Sun


Here's a spin off of eryksun's Windows specific solution (using only built-in python modules) dropping the csv import and directly filtering tasklist output for an exe name:

import subprocess

def isWindowsProcessRunning( exeName ):                    
    process = subprocess.Popen( 
        'tasklist.exe /FO CSV /FI "IMAGENAME eq %s"' % exeName,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        universal_newlines=True )
    out, err = process.communicate()    
    try   : return out.split("\n")[1].startswith('"%s"' % exeName)
    except: return False
like image 37
BuvinJ Avatar answered Oct 06 '22 00:10

BuvinJ