Implementation function: automatically run after starting, print the user CPU usage per second, automatically calculate and print the average value and maximum value at the end of the script.
#! /usr/bin/python # -*-coding: utf-8 -*- import subprocess import os import time cmd = "top -bn 1 | grep 'Cpu(s)' | awk -F'[\" \"%]+' '{print $3}'" Count = 0 total = 0.0 max_use = 0.0 Try: while True: cpu_usage = OS.popen (CMD).readline().strip() count = count + 1; Cpu_use = float(cpu_usage) total = total + cpu_use max_use = Max (max_use, cpu_use) cpu_tip = "user CPU: " + cpu_usage + "%" print(cpu_tip) time.sleep(1) except KeyboardInterrupt: if count ! Print ("user CPU per: "+ STR (per)) print("user CPU Max:" + STR (max_use))Copy the code