[Frubar Paste] Hosted by SkyLime - Chat with us at XChannel IRC

Posted by Wiedi on Sat 5th Dec 14:02
download

  1. #!/usr/bin/python
  2.  
  3. import subprocess
  4. from optparse import OptionParser
  5.  
  6. def get_process_stats(column=0):
  7.         stats = {}
  8.         process_list = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE).communicate()[0].strip().split('\n')[1:]
  9.         for process in process_list:
  10.                 process_info = process.split()
  11.                 key = process_info[column]
  12.                 if key in stats:
  13.                         stats[key] += 1
  14.                 else:
  15.                         stats[key] = 1
  16.         return stats
  17.  
  18. def get_app_process_stats():
  19.         return get_process_stats(10)
  20.  
  21. def get_user_process_stats():
  22.         return get_process_stats(0)
  23.  
  24. def print_stats(stats, minimum = 0):
  25.         from operator import itemgetter
  26.         for line in sorted(stats.items(), key=itemgetter(1), reverse=True):
  27.                 if line[1] > minimum:
  28.                         print "%20s: %s" % line
  29.  
  30.  
  31. def main():
  32.         parser = OptionParser("usage: %prog [-m] [-a|-u]")
  33.         parser.add_option("-m", "--minimum", dest="minimum", default=0, type="int",
  34.                                 help="only show process information which occurs at least minimum times")
  35.         parser.add_option("-a", "--application", dest="app", action="store_true",
  36.                                 help="count instances of applications running (default)", default=True)
  37.         parser.add_option("-u", "--user", dest="app", action="store_false",
  38.                                 help="count processes per user")
  39.  
  40.         (options, args) = parser.parse_args()
  41.  
  42.         if options.app:
  43.                 stats = get_app_process_stats()
  44.         else:
  45.                 stats = get_user_process_stats()
  46.  
  47.         print_stats(stats, options.minimum)
  48.  
  49.        
  50. if __name__ == '__main__':
  51.         main()


Submit a correction or amendment below. (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

New posts are disabled. Archive only, sorry.