pstree.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python
  2. # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """
  6. Similar to 'ps aux --forest' on Linux, prints the process list
  7. as a tree structure.
  8. $ python examples/pstree.py
  9. 0 ?
  10. |- 1 init
  11. | |- 289 cgmanager
  12. | |- 616 upstart-socket-bridge
  13. | |- 628 rpcbind
  14. | |- 892 upstart-file-bridge
  15. | |- 907 dbus-daemon
  16. | |- 978 avahi-daemon
  17. | | `_ 979 avahi-daemon
  18. | |- 987 NetworkManager
  19. | | |- 2242 dnsmasq
  20. | | `_ 10699 dhclient
  21. | |- 993 polkitd
  22. | |- 1061 getty
  23. | |- 1066 su
  24. | | `_ 1190 salt-minion...
  25. ...
  26. """
  27. from __future__ import print_function
  28. import collections
  29. import sys
  30. import psutil
  31. def print_tree(parent, tree, indent=''):
  32. try:
  33. name = psutil.Process(parent).name()
  34. except psutil.Error:
  35. name = "?"
  36. print(parent, name)
  37. if parent not in tree:
  38. return
  39. children = tree[parent][:-1]
  40. for child in children:
  41. sys.stdout.write(indent + "|- ")
  42. print_tree(child, tree, indent + "| ")
  43. child = tree[parent][-1]
  44. sys.stdout.write(indent + "`_ ")
  45. print_tree(child, tree, indent + " ")
  46. def main():
  47. # construct a dict where 'values' are all the processes
  48. # having 'key' as their parent
  49. tree = collections.defaultdict(list)
  50. for p in psutil.process_iter():
  51. try:
  52. tree[p.ppid()].append(p.pid)
  53. except (psutil.NoSuchProcess, psutil.ZombieProcess):
  54. pass
  55. # on systems supporting PID 0, PID 0's parent is usually 0
  56. if 0 in tree and 0 in tree[0]:
  57. tree[0].remove(0)
  58. print_tree(min(tree), tree)
  59. if __name__ == '__main__':
  60. main()