how do I get the process list in Python?

后端 未结 4 1197
感情败类
感情败类 2020-12-06 01:51

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.

4条回答
  •  Happy的楠姐
    2020-12-06 02:29

    On Linux, with a suitably recent Python which includes the subprocess module:

    from subprocess import Popen, PIPE
    
    process = Popen(['ps', '-eo' ,'pid,args'], stdout=PIPE, stderr=PIPE)
    stdout, notused = process.communicate()
    for line in stdout.splitlines():
        pid, cmdline = line.split(' ', 1)
        #Do whatever filtering and processing is needed
    

    You may need to tweak the ps command slightly depending on your exact needs.

提交回复
热议问题