| OLD | NEW |
| (Empty) | |
| 1 #!/usr/bin/python |
| 2 # Copyright 2015 The Chromium Authors. 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 """Prints out the most active processes running in the background. |
| 7 |
| 8 Example usage: |
| 9 ./cpu_usage.py --nproc==[THE NUMBER OF PROCESSES TO PRINT OUT] |
| 10 """ |
| 11 |
| 12 |
| 13 import argparse |
| 14 import json |
| 15 import platform |
| 16 import subprocess |
| 17 import sys |
| 18 |
| 19 LINUX_START_LINE_NUM = 7 |
| 20 WINDOWS_START_LINE_NUM = 3 |
| 21 |
| 22 def _parse_line(line): |
| 23 """Parses a line from top output |
| 24 |
| 25 Args: |
| 26 line(str): a line from top output that contains the |
| 27 information of a process |
| 28 |
| 29 Returns: |
| 30 An dictionary with useful information about the process |
| 31 |
| 32 """ |
| 33 token_list = line.strip().split() |
| 34 if platform.system() == "Windows": |
| 35 process_object = {'pid':token_list[6], |
| 36 'pCPU':token_list[5], |
| 37 'command':token_list[7]} |
| 38 else: |
| 39 process_object = {'pid':token_list[0], 'user':token_list[1], |
| 40 'pCPU':token_list[8], 'pMEM':token_list[9], |
| 41 'command':token_list[11]} |
| 42 return process_object |
| 43 |
| 44 def _get_top_processes(n): |
| 45 """Fetches the top processes returned by top command |
| 46 |
| 47 Args: |
| 48 n(int): the number of processes to get |
| 49 |
| 50 Returns: |
| 51 A list of dictionaries, each representing one of the top processes |
| 52 |
| 53 """ |
| 54 if platform.system() == "Windows": |
| 55 processes = subprocess.check_output('powershell "ps | sort -desc cpu"', |
| 56 shell=True).split('\n') |
| 57 top_processes = processes[WINDOWS_START_LINE_NUM: |
| 58 WINDOWS_START_LINE_NUM + n] |
| 59 else: |
| 60 processes = subprocess.check_output(["top","-n 1","-b"]).split('\n') |
| 61 top_processes = processes[LINUX_START_LINE_NUM: |
| 62 LINUX_START_LINE_NUM + n] |
| 63 parsed_top_processes = [_parse_line(process) \ |
| 64 for process in top_processes] |
| 65 return parsed_top_processes |
| 66 |
| 67 |
| 68 def main(): |
| 69 parser = argparse.ArgumentParser( |
| 70 description='Take a snapshot of CPU usage.') |
| 71 parser.add_argument('--nproc', dest='nproc', default=10, |
| 72 help='the number of processes to display') |
| 73 args = parser.parse_args() |
| 74 top_processes = _get_top_processes(int(args.nproc)) |
| 75 print(json.dumps(top_processes)) |
| 76 return 0 |
| 77 |
| 78 if __name__ == "__main__": |
| 79 main() |
| OLD | NEW |