Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Created June 8, 2016 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cslarsen/7e2ae926706f9d18287fdbc87850eb0f to your computer and use it in GitHub Desktop.
Save cslarsen/7e2ae926706f9d18287fdbc87850eb0f to your computer and use it in GitHub Desktop.
Prints PIDs for given program basename (or wildcard if not found)
#!/usr/bin/env python3
from collections import defaultdict
import os
import sys
def read_cmdline(file):
try:
with open(file, "rb") as f:
cmd = str(f.read(), encoding="utf-8")
if cmd is not None:
return cmd.replace("\x00", " ")
except:
pass
def getprogs():
# Index on the basename of cmdline
basenames = defaultdict(lambda: [])
# Index on the full command line
fullnames = defaultdict(lambda: [])
for pid in os.listdir("/proc/"):
if pid.isdigit():
pid = int(pid)
cmd = read_cmdline("/proc/%d/cmdline" % pid)
if cmd is not None:
basenames[os.path.basename(cmd.split(" ")[0])].append(pid)
fullnames[cmd].append(pid)
return basenames, fullnames
if __name__ == "__main__":
if ("-h" in sys.argv) or ("--help" in sys.argv):
print("Usage: pid name [ name]")
print("Returns pids of program basenames.")
print("Example: pid vim # prints pids for all vim procs")
sys.exit(0)
self = os.getpid()
basenames, fullnames = getprogs()
for prog in sys.argv[1:]:
if prog in basenames:
for pid in basenames[prog]:
if pid != self:
print(pid)
else:
for cmd, pids in fullnames.items():
if prog in cmd:
for pid in pids:
if pid != self:
print(pid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment