感谢Vamei的matplotlib 的文章:
http://www.cnblogs.com/vamei/archive/2013/01/30/2879700.html
代码如下:
首先用psutil 获得进程的CPU 使用率,然后再用matplotlib绘图。
-
import psutil
-
import sys
-
import re
-
ll=[]
-
def processinfo(pid):
-
p=psutil.Process(pid)
-
for i in range(10):
-
#print(p.cpu_percent(interval=3))
-
ll.append(p.cpu_percent(interval=1))
-
return ll
-
-
-
#print(processinfo(1051))
-
import random
-
from matplotlib.figure import Figure
-
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
-
def plot_cpu_usage(y):
-
x=list(range(3,31,3)) #x
-
#I will manipulate Y if ll is empty
-
if not y:
-
y=[random.randint(1,5) for i in range(10)] #y
-
-
fig = Figure()
-
canvas = FigureCanvas(fig)
-
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
-
line, = ax.plot(x,y)
-
ax.set_title("cpu usage for PID 1051")
-
ax.set_xlabel(" time in seconds ")
-
ax.set_ylabel(" cpu usage in %")
-
canvas.print_figure('demo.jpg')
-
-
#processinfo(1051)
-
plot_cpu_usage(ll)
另外我发现3.5的python 跟matplotlib 配合使用的时候,无法使用GTKAgg 作为backend.
-
#next 5 lines error out on Kali linux with python3.5, but works with python2.7
-
import matplotlib as mpl
-
mpl.use('GTKAgg') #use GTK UI
-
mpl.use('GTKCairo')
-
import matplotlib.pyplot as plt
-
plt.plot([1,3,2,4])
-
plt.show()
但是我可以正常的import Gtk
-
python3
-
import gi
-
gi.require_version('Gtk','3.0')
-
from gi.repository import Gtk as gtk
阅读(1530) | 评论(0) | 转发(0) |