最近在项目中需要一个可以长时间运行并监控某个进程的CPU和内存使用信息的脚本。于是很自然想到用Python来实现。笔者使用的是psutil。代码如下所示。
#encoding=utf-8
import psutil
import time
import sys
"""
这个脚本用于监控某个进程的CPU和内存使用情况,将信息记录到文件中
"""
if __name__ == '__main__':
"""参数1:进程PID 参数2:保存的文件名(可选) 参数3:时间间隔(可选)
"""
pid = sys.argv[1]
file_name = sys.argv[2] if len(sys.argv) > 2 else 'Test.txt'
interval = float(sys.argv[3]) if len(sys.argv) > 3 else 1800
p = psutil.Process(int(pid))
try:
while True:
f = open(file_name, 'a')
f.write('time: %s\tcpu percent: %f\tmemory usage:%d\n' % (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())),
p.get_cpu_percent(interval=1.0),
p.get_memory_info()[0]))
f.close()
# 每一段时间记录一次进程的CPU和内存使用信息
time.sleep(interval)
except KeyboardInterrupt:
# 中断退出
print 'Exit!'
finally:
f.close()
网友评论
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Silence'
import time
import sys
import psutil
'''
这个脚本用于监控某个进程的CPU和内存使用情况,
将信息记录到文件中
参数1:进程PID 参数2:保存的文件名(可选) 参数3:时间间隔(可选)
'''
def monitorProcess(process_id):
process_info = psutil.Process(process_id)
record = 'time: %s\tcpu percent: %f\tmemory usage: %d\n' % (
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),
process_info.cpu_percent(interval=1.0),
process_info.memory_info()[0]
)
return record
def save_toFile(file_name, record):
with open(file_name, 'a') as file:
file.write(record)
def monitorProcess_once(process_id, file_name):
record = monitorProcess(process_id)
save_toFile(file_name, record)
def monitorProcessAndSaveRecordToFile(process_id, file_name, interval_time):
try:
while True:
monitorProcess_once(process_id, file_name)
time.sleep(interval_time)
except KeyboardInterrupt:
print 'Exit!'
if __name__ == '__main__':
process_id = int(sys.argv[1])
file_name = sys.argv[2] if len(sys.argv) >= 3 else ('process_mornitor_test.txt')
interval_time = int(sys.argv[3]) if len(sys.argv) >= 4 else (5)
monitorProcessAndSaveRecordToFile(process_id, file_name, interval_time)