On Linux, we can find processes and their names via the /proc filesystem.
Names are in /proc/xxx/comm, so we need only read this and pass it to re.search.
I wrote this so as to not need to pip install pgrep for what this function does.
#!/usr/bin/env python
# Poor mans pgrep, can just use this instead of having to install the pgrep
# module
import re
import sys
from glob import glob
from re import I # so we can use mypgrep.I without having to import re
def pgrep(pat,flags=0):
'''pgrep(pattern, flags=0)
flags are those in the re module and are passed to re.compile
just put the output of this into dict() to get a dict'''
r = re.compile(pat,flags)
procs = glob("/proc/[0-9]*/comm")
matches = []
for proc in procs:
pid = int(proc.split("/")[2])
try:
with open(proc) as f:
name = f.read().rstrip()
except Exception as e:
print(f"# Exception {e} ({type(e)}) reading {proc}",file=sys.stderr)
continue
if r.search(name):
matches.append((pid,name))
return matches
if __name__ == "__main__":
# random demo and test
print(pgrep_list("init"))
print(pgrep_list("Init",I))
d = dict(pgrep_list("init"))
print(d)
print(pgrep_dict("init"))
print(pgrep_dict("Init",I))
print("\n".join(f"{x:<10} {y}" for x,y in pgrep_list("bash")))
exit()