【问题标题】:Python3 Matplotlib psutil script not runningPython3 Matplotlib psutil 脚本未运行
【发布时间】:2020-06-30 19:40:50
【问题描述】:

所以我有一个问题。我有两个脚本正在运行,一个是每秒的 CPU 和时间记录器,用于将 CPU 使用情况记录到文本文件中。另一个是将文本文件读入图形的脚本,但图形不是统一轴,单位不增加,我得到错误的输出视图。

Script1:将 PSU 和时间记录到 txt 文件

import psutil import time
print(str(time.strftime("%H:%M:%S", time.localtime())) + ", " +
      str(psutil.cpu_percent(interval=1)))
f = open("example.txt", "a+")
f.write(str(time.strftime("%H:%M:%S", time.localtime())) + 
      ", " + str(psutil.cpu_percent(interval=1)) + " \n")

程序 2:绘制图表

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style

style.use('fivethirtyeight')

fig = plt.figure() ax1 = fig.add_subplot(1,1,1)

def animate(i):
    graph_data = open ('example.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            x, y = line.split(',')
            xs.append(x)
            ys.append(y)
    ax1.clear()
    ax1.plot(xs, ys)

ani = animation.FuncAnimation(fig, animate, interval=1000) plt.show()

Script2 output

如果可以将其制成一个脚本,那就太好了,但我正在努力学习基础知识。我认为这是写入 txt 文件的字符串问题,但不知道为什么字符串在 txt 文件中很重要。

【问题讨论】:

    标签: python python-3.x matlab psutil


    【解决方案1】:

    我想你需要在TXT o CSV文件中写入的字符串将由(在CSV之前更容易阅读)生成:

    import time
    import psutil
    import csv
    
    num_measures = 10
    with open("cpu_pcnt.csv", mode='w') as file:
        for _ in range(num_measures): 
            str_time = time.strftime("%H:%M:%S")
            cpu_pcnt = psutil.cpu_percent(interval=1)
            str_data = f"{str_time},{cpu_pcnt}\n"
            file.write(str_data)
    

    然后,将 datetime 对象中的时间转换为绘图,并将 pcu 百分比转换为浮点数:

    def animate(i):
        xs = []
        ys = []
        
        with open("cpu_pcnt.csv") as file:
            reader = csv.reader(file)
            for line in reader:
                xs.append(datetime.strptime(line[0], "%H:%M:%S"))
                ys.append(float(line[1]))
                
        ax1.clear()
        ax1.plot(xs, ys)
    

    【讨论】:

    • 回溯(最近一次调用最后):文件“init.py”,第 196 行,处理中 func(*args, **kwargs) 文件“animation.py” ,第 951 行,在 _start self._init_draw() 文件“animation.py”,第 1743 行,在 _init_draw self._draw_frame(next(self.new_frame_seq())) 文件“animation.py”,第 1766 行,在 _draw_frame self. _drawn_artists = self._func(framedata, *self._args) File "Plotter.py", line 15, in animate reader = csv.reader(file) NameError: name 'csv' is not defined
    猜你喜欢
    • 2020-01-05
    • 2019-10-25
    • 1970-01-01
    • 2017-05-24
    • 2017-05-22
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多