Show all python processes

How to display list of running processes python

While we now have the field (and a few others to boot), you’ll notice that for processes that do not announce their description (most of them, Windows programmers be lazy apparently) or services without a description — the description value just contains the executable name i.e. if you’re running plain old Notepad, while Task Manager UI will show you as Description, its dictionary entry will have — that is because Task Manager UI uses a completely different approach to task list and gets the description directly from the process executable. Solution 1: A textbook answer would be to use module like this: That generates a dictionary with process id as key, and process name as value for current user processes.

How do I show a list of processes for the current user using python?

A textbook answer would be to use psutil module like this:

import psutil,getpass,os user_name = getpass.getuser() process_dict =

That generates a dictionary with process id as key, and process name as value for current user processes.

That approach looks good but on my Windows server machine (where I don’t have admin privileges) I couldn’t get proc.username() without getting psutil.AccessDenied exception. So I tried to catch the exception in an helper routine, which led me to another strange error, so I dropped the whole idea and built a Windows-only solution based on tasklist command:

tasklist /FI "USERNAME eq %USERNAME%" /FO CSV 

which, adapted to python and with the same convenient pid => username dictionary format translates as:

import csv,subprocess def get_current_user_processes(): csv_output = subprocess.check_output(["tasklist","/FI","USERNAME eq <>".format(os.getenv("USERNAME")),"/FO","CSV"]).decode("ascii","ignore") cr = csv.reader(csv_output.splitlines()) next(cr) # skip title lines return

It tells tasklist to keep only current user processes, and to use csv output format so it can be parsed easily with the csv module. Then, we keep only the 2 first columns (name & pid) and convert pid to integer for good measure.

Читайте также:  Обратная связь

It creates dictionaries like this:

Now each individual process can be examined more deeply with psutil without risking getting access denied or other strange errors:

d = get_current_user_processes() processes = [proc for proc in psutil.process_iter() if proc.pid in d] 
import subprocess ps = subprocess.Popen('ps -ef', shell=True, stdout=subprocess.PIPE) print ps.stdout.readlines() 

You can try using psutil.process_iter(). For instance:

import psutil pids=[process.pid for process in psutil.process_iter() if process.username == 'root'] 

In this case I supposed you wanted to find every process run by the «root» user

Which python script is running

You can use command below in linux to get which script is runing.

And you will see which python scrip is running.

Get list of running windows applications using python, 2 Answers. Sorted by: 6. You could use powershell instead of WMIC to get the desired list of applications: import subprocess cmd = ‘powershell «gps | where | select Description’ proc = subprocess.Popen (cmd, shell=True, stdout=subprocess.PIPE) for line in proc.stdout: if line.rstrip (): # only …

Tasklist command with description

That’s a bit trickier than you might imagine and you really need a good reason to go through all the trouble to justify it. First of all, Task Manager UI doesn’t get its information from tasklist.exe , although you can get pretty close with:

import csv import subprocess try: tl_out = subprocess.check_output(["tasklist", "/fo", "csv", "/v"]) except subprocess.CalledProcessError as e: print("Call to `tasklist` failed: <>".format(e)) exit(1) tl_csv = csv.DictReader(tl_out.splitlines()) for row in tl_csv: print(row) # prints a dict for each task with all available fields # Available fields (may vary from platform to platform) are: # 'Status', 'CPU Time', 'Image Name', 'Session Name', 'Window Title', # 'PID', 'User Name', 'Session#', 'Mem Usage' 

However, to get to the Description field (and a lot others from the Task Manager UI) you’ll have to pull the data from WMI at the very least. To make matters worse, WMIC on Windows 7 has a bug when exporting to CSV making the whole thing even more complicated as for maximum portability we need to use the list format and parse it ourselves:

import subprocess try: wmi_out = subprocess.check_output(["wmic", "process", "list", "full", "/format:list"]) except subprocess.CalledProcessError as e: print("Call to `wmic` failed: <>".format(e)) exit(1) # parse the WMI list: wmi_entries = [] for task in wmi_out.strip().split("\r\r\n\r\r\n"): wmi_entries.append(dict(e.split("=", 1) for e in task.strip().split("\r\r\n"))) for row in wmi_entries: print(row) # prints a dict for each task with all available fields # Available fields (may vary from platform to platform) are: # 'CSName', 'CommandLine', 'Description', 'ExecutablePath', 'ExecutionState', 'Handle', # 'HandleCount', 'InstallDate', 'KernelModeTime', 'MaximumWorkingSetSize', # 'MinimumWorkingSetSize', 'Name', 'OSName', 'OtherOperationCount', 'OtherTransferCount', # 'PageFaults', 'PageFileUsage', 'ParentProcessId', 'PeakPageFileUsage', # 'PeakVirtualSize', 'PeakWorkingSetSize', 'Priority', 'PrivatePageCount', 'ProcessId', # 'QuotaNonPagedPoolUsage', 'QuotaPagedPoolUsage', 'QuotaPeakNonPagedPoolUsage', # 'QuotaPeakPagedPoolUsage', 'ReadOperationCount', 'ReadTransferCount', 'SessionId', # 'Status', 'TerminationDate', 'ThreadCount', 'UserModeTime', 'VirtualSize', # 'WindowsVersion', 'WorkingSetSize', 'WriteOperationCount', 'WriteTransferCount' 

Code Update for Python3 (use encode for bytes-wise search):

s1 = "\r\r\n\r\r\n".encode() s2 = "\r\r\n".encode() for task in wmi_out.strip().split(s1): wmi_entries.append(dict(e.split("=".encode(), 1) for e in task.strip().split(s2))) 

If you don’t need all these fields, you can always restrict wmic to get you the fields you want (i.e. wmi_out = subprocess.check_output([«wmic», «process», «get», «ProcessId,ExecutablePath,Description», «/format:list»]) to get only Description per ProcessId ).

But don’t think your troubles are over — we just started. While we now have the Description field (and a few others to boot), you’ll notice that for processes that do not announce their description (most of them, Windows programmers be lazy apparently) or services without a description — the description value just contains the executable name i.e. if you’re running plain old Notepad, while Task Manager UI will show you Notepad as Description, its dictionary entry will have notepad.exe — that is because Task Manager UI uses a completely different approach to task list and gets the description directly from the process executable.

So you actually need an additional step to retrieve the executable description directly from its resources table, which is probably the ‘easiest’ to do by invoking the Win32 API to get to the description, so you need to install the pyWin32 module first:

import subprocess import win32api # gets executable description via W32API def get_executable_desc(path, default=''): try: language, codepage = win32api.GetFileVersionInfo(path, "\\VarFileInfo\\Translation")[0] return win32api.GetFileVersionInfo(path, "\\StringFileInfo\\\\FileDescription".format(language, codepage)) or default except: return default try: wmi_out = subprocess.check_output(["wmic", "process", "list", "full", "/format:list"]) except subprocess.CalledProcessError as e: print("Call to `tasklist` failed: <>".format(e)) exit(1) # parse the WMI list: wmi_entries = [] for task in wmi_out.strip().split("\r\r\n\r\r\n"): entry = dict(e.split("=", 1) for e in task.strip().split("\r\r\n")) entry['Description'] = get_executable_desc(entry.get("ExecutablePath", None), entry.get("Description", None)) wmi_entries.append(entry) for row in wmi_entries: print(row) # prints a dict for each task with all available fields 

Voilà! Descriptions are now populated (where available, or at least hold the executable name), but since we had to use Win32 API to get to the descriptions, we might as well get the tasks list through it — it’s faster and more concise:

from win32api import GetFileVersionInfo, OpenProcess from win32con import PROCESS_QUERY_INFORMATION, PROCESS_VM_READ from win32process import EnumProcesses, EnumProcessModules, GetModuleFileNameEx import pywintypes # gets executable description via W32API def get_executable_desc(path, default=''): try: language, codepage = GetFileVersionInfo(path, "\\VarFileInfo\\Translation")[0] return GetFileVersionInfo(path, "\\StringFileInfo\\\\FileDescription".format(language, codepage)) or default except: return default # gets the process list via W32API def get_process_list(): proc_list = [] processes = EnumProcesses() if not processes: return [] # optionally raise an exception, no ProcessIds could be obtained for proc in processes: try: handle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, pywintypes.FALSE, proc) modules = EnumProcessModules(handle) if not modules: continue # task died in the meantime? path = GetModuleFileNameEx(handle, modules[0]) proc_list.append() except pywintypes.error as e: continue # optionally report the error stored in `e` return proc_list tasks = get_process_list() for row in tasks: print(row) # prints a dict for each task with ProcessId, ExecutablePath and Description fields 

This will only get ProcessId, ExecutablePath and Description but you can further explore Win32 API if you need more fields.

Again, I don’t see of what value the Description field is to go through all this trouble but if you really, really want it — this is how to get it.

Unix — how do I get the process list in Python?, How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes. python unix kill ps processlist. Share. Improve this question. Follow edited Nov 14, 2013 at 13:08. oHo.

Источник

How to Find and List All Running Processes in Python

In this tutorial, we are going to learn how to find and list all running processes in Python. It is a very simple program.

Python program to find and list all running processes

To do this, we need psutil library. Let us install it.

Now, we need to import it into our program.

We have a method called process_iter which iterates all the running processes. This method is present within the psutil library. That’s the reason we have imported it into our program.

c=0 for process in psutil.process_iter (): c=c+1 Name = process.name () # Name of the process # ID of the process print ("Process name =", Name ,",","Process \nTotal number of running process are ", c)

For every process that is running, we are getting its name and ID using the name and pid methods.

To count the total number of running processes, I used the variable ‘c’ and incremented it for every process.

Process name = System Idle Process , Process name = System , Process name = Registry , Process name = RuntimeBroker.exe , Process name = smss.exe , Process name = svchost.exe , Process name = csrss.exe , Process . . Process name = chrome.exe , Process name = svchost.exe , Process name = svchost.exe , Process name = svchost.exe , Process name = csrss.exe , Process name = ApntEx.exe , Process number of running process are 145

The output varies from system to system. It depends on the processes that are running at that moment. At this moment there are 145 running processes in my system.

Источник

Оцените статью