Get process name by PID Get process name by PID python python

Get process name by PID


Under Linux, you can read proc filesystem. File /proc/<pid>/cmdline contains the commandline.


Try PSUtil -> https://github.com/giampaolo/psutil

Works fine on Windows and Unix, I recall.


For Windows

A Way to get all the pids of programs on your computer without downloading any modules:

import ospids = []a = os.popen("tasklist").readlines()for x in a:      try:         pids.append(int(x[29:34]))      except:           passfor each in pids:         print(each)

If you just wanted one program or all programs with the same name and you wanted to kill the process or something:

import os, sys, win32apitasklistrl = os.popen("tasklist").readlines()tasklistr = os.popen("tasklist").read()print(tasklistr)def kill(process):     process_exists_forsure = False     gotpid = False     for examine in tasklistrl:            if process == examine[0:len(process)]:                process_exists_forsure = True     if process_exists_forsure:         print("That process exists.")     else:        print("That process does not exist.")        raw_input()        sys.exit()     for getpid in tasklistrl:         if process == getpid[0:len(process)]:                pid = int(getpid[29:34])                gotpid = True                try:                  handle = win32api.OpenProcess(1, False, pid)                  win32api.TerminateProcess(handle, 0)                  win32api.CloseHandle(handle)                  print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid))                except win32api.error as err:                  print(err)                  raw_input()                  sys.exit()    if not gotpid:       print("Could not get process pid.")       raw_input()       sys.exit()   raw_input()   sys.exit()prompt = raw_input("Which process would you like to kill? ")kill(prompt)

That was just a paste of my process kill program I could make it a whole lot better but it is okay.