Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
Creating Process Dictionary

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??

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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()}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda