Python 指定名称对 CPU的使用情况监测

# -*- coding: utf-8 -*-
import os
import sys
import psutil
import string
import re
import time
import datetime
import csv

# Get PID of a process, 此函数得到 名称为name的pid

def get_pid(name):
    process_list = psutil.get_process_list()
    # print process_list
    regex = "pid=(\d+),\sname=\'" + name + "\'"
    # print regex
    pid = 0
    for line in process_list:
        process_info = str(line)
        ini_regex = re.compile(regex)
        result = ini_regex.search(process_info)
        if result is not None:
            pid = string.atoi(result.group(1))
            # print pid
            return pid

pid = get_pid('slam_karto') # 需要监测的进程名称

# 文本名称
filename = 'cpu_supervise.csv'

fileHeader = ["time","timestamp", "Total","SlamKarto"]

csvFile = open(filename, "a")

writer = csv.writer(csvFile)

writer.writerow(fileHeader)

info = []
while 1:

    info[:] = [] #    清空list

    info.append(datetime.datetime.now())

    info.append(int(time.time()))
    # 总的cpu 消耗
    Total_cpu_percent = psutil.cpu_percent(interval=1,percpu=False)

    info.append(Total_cpu_percent)
        # Slam_Karto 占用的 cpu 消耗
    p1=psutil.Process(pid)       
    p1_cpu_percent = p1.get_cpu_percent(interval=1) 

    info.append(p1_cpu_percent)
    # cpu_info = str(Total_cpu_percent) + ',' + str( p1_cpu_percent)
    # print cpu_info    
    print info

    writer.writerow(info)


csvFile.close()

你可能感兴趣的:(Python)