I am working on a project which needs the list of PID of all the running process. I want it via python programming language. How to get it? Thanks in adv.
Asked
Active
Viewed 7,472 times
5
-
1@AkshayNevrekar, Yes it solves partially my problem but this solution seems specific to windows OS. I want generic solution. Thanks. – Jan 31 '19 at 14:43
1 Answers
8
If you are on Linux just use subprocess.Popen
to spawn the ps - ef
command, and then fetch the second column from it. Below is the example.
import subprocess as sb
proc_list = sb.Popen("ps -ef | awk '{print $2} ' ", stdout=sb.PIPE).communicate()[0].splitlines()
for pid in proc_list:
print(pid)
If you want to keep it platform independent use psutil.pids()
and then iterate over the pids. You can read more about it here, it has bunch of examples which demonstrates what you are probably trying to achieve.
Hope this helps.
Please execuse any typo if any, i am just posting this from mobile device.
If you want a dictionary with pid and process name, you could use the following code:
import psutil
dict_pids = {
p.info["pid"]: p.info["name"]
for p in psutil.process_iter(attrs=["pid", "name"])
}

Jean-Francois T.
- 11,549
- 7
- 68
- 107

Rohit
- 3,659
- 3
- 35
- 57