0

Given a proccess name(PID is unkown), how can i detect when a proccess has been ended(Also how can i find out the PID given a proccess name)? Also, I'm doing this for windows explorer, so how would I track the proccess name as it changes as the user moves thorugh directories.

I'm using Python 2.7 and windows if that helps.

Thank you

John Hon
  • 7
  • 1
  • 2

1 Answers1

1

As Padraic Cunningham wrote here: Python: How to get PID by process name? In order to get pid from process-name:

from subprocess import check_output
def get_pid(name):
    return int(check_output(["pidof","-s",name]))

As Mat wrote here: https://stackoverflow.com/a/6767792/5088142 In order to get status of a process using its pid your can use psutil https://github.com/giampaolo/psutil

import psutil
print psutil.Process(pid).status

Edit: You can combine those two parts into the following code:

from subprocess import check_output
import psutil
def get_pid(name):
    return int(check_output(["pidof","-s",name]))
def get_status(name)
    pid = get_pid(name)
    print psutil.Process(pid).status
Community
  • 1
  • 1
Yaron
  • 10,166
  • 9
  • 45
  • 65
  • Thank you for that, but another question, how would i be able to constantly test for it ( i'm sorry im quite new, but i realise that checking for an update in an envrionment is important in porgramming) thank you once again :) – John Hon Apr 13 '16 at 14:24
  • I've added a new function which combines the two parts of code. you can call the function get_status("process_name") and get the process status. (note that you'll need to install psutil) – Yaron Apr 13 '16 at 14:29
  • thx, but would you happen to know a way to constantly check for this throughout my code, or is that not possible? thank you anyway :) – John Hon Apr 13 '16 at 14:31
  • you can grab all pid with psutil `import psutil pids = [p for p in psutil.pids() if psutil.Process(p).name() == process_name] print(pids)` – Samuel LEMAITRE Apr 13 '16 at 15:07
  • Please provide detailed scenario, so we'll be able to understand your needs. What do you want to check? How often? – Yaron Apr 13 '16 at 15:09