2

My Goal: I need to create a function that retrieves the PID and Name of each process and returns them in a dictionary. I will be uploading this to Django and really need two different dictionaries. 1 with every running process name and PID and another with all installed names and PIDs. So far I can get it to print the dictionary well but not return correctly. Maybe I am calling it wrong. I am newer to this.

import psutil
def pid_name():
    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid', 'name'])
        except psutil.NoSuchProcess:
            pass
        else:
            return pinfo

If you were to sub "return" for print the dict will print fine. How to I call that dict from here? Is it even returning correctly??

Joe
  • 2,641
  • 5
  • 22
  • 43

1 Answers1

1

You are returning only the first result because your return statement is inside the for block. Since you can't create a dictionary with duplicate keys, you should return a list of dictionaries instead. Try a list comprehension to return all the processes:

import psutil

def pid_name():
    return [proc.as_dict(attrs=['pid', 'name']) for proc in psutil.process_iter()]

Update:

If you are trying to create a dictionary with pids as keys and names as values, it's even easier:

def pid_name():
    return {proc.pid: proc.name() for proc in psutil.process_iter()}
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • Thanks, that makes sense. But my real problem now is how do I format the results to i can just have the id associated with the name. That way I can populate the fields on django. Every thing I have tried in doing so errors out on me – Joe Apr 26 '17 at 02:53
  • Are you trying to create a dictionary with `pid`s as keys and `name`s as values? If yes, see my update. – Selcuk Apr 26 '17 at 04:10
  • Yes! I will try that right now! This is for a class and even the teacher was impressed with how nice your code was. Said it was 'beautiful'. haha. The assignment is to post data to a Django site. So I am trying to create two fields in my Django Model that will take these values. – Joe Apr 26 '17 at 16:50