解决 ModuleNotFoundError: No module named matplotlib.pyplot 问题

解决 ModuleNotFoundError: No module named matplotlib.pyplot 问题

最近在想把iperf打流的数据,自动绘图,但在运行的时候会报错。

1. 报错提示

Traceback (most recent call last):
  File "E:\python\iperf.py", line 2, in <module>
    import matplotlib.pyplot as plt
  File "E:\python\iperf.py", line 2, in <module>
    import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'matplotlib.pyplot'

2. 解决方案

我通过卸载重装matplotlib解决了问题:

1.pip卸载matplotlib

python -m pip uninstall matplotlib

2.pip安装jupyter

python -m pip install jupyter

3.pip安装matplotlib

python -m pip install matplotlib

3. 比较粗糙的例子

from fileinput import filename
import re
from time import sleep
import matplotlib.pyplot as plt
import numpy as np
import os


filename="iperf3-4.log"
test_time=60

# RX test
#cmd = "iperf3 -c 192.168.21.1 -i 1 -w 2M -P 5 -t %d --logfile %s" % (test_time, filename)

# TX test
cmd = "iperf3 -c 192.168.21.1 -i 1 -w 2M -P 5 -t %d --logfile %s -R" % (test_time, filename)

if os.path.exists(filename):
    os.remove(filename)

os.system(cmd)

sleep(1)

# 先处理文件,把最后的统计信息删除
lineList = []
matchPattern1 = re.compile(r'sender')
matchPattern2 = re.compile(r'receiver')
file = open(filename,'r', encoding='UTF-8')
while 1:
    line = file.readline()
    if not line:
        print("Read file End or Error")
        break
    elif matchPattern1.search(line):
        pass
    elif matchPattern2.search(line):
        pass
    else:
        lineList.append(line)
file.close()
file = open(filename, 'w', encoding='UTF-8')
for i in lineList:
    file.write(i)
file.close()

# 读取文件,绘图
time_list = []
rate_list = []
with open(filename, 'r') as f:# iperf-log.txt为iperf日志文件名 # encoding='gb18030', errors='ignore'
    row_data = f.readlines() # 读取iperf日志文件的每一行至一个list中
    for line in row_data:    # 利用正则表达式进行匹配,可根据实际情况更改匹配内容
		# 但线程
#       time = re.findall(r"-(.*) sec", line)
#       rate = re.findall(r"MBytes  (.*) Mbits", line)

		# 多线程
        patt=r"[SUM].*-(.*) sec"
        time = re.findall(patt, line)
#        print(time)

        patt=r"[SUM].*Bytes(.*) Mbits/sec"
        rate = re.findall(patt, line)
#        print(rate)
        if(len(time) > 0 and "time" != "[]" and "rate" != "[]"):     # 当前行中有吞吐和时间数据时对数据进行存储
#            print(time)
#            print(rate)
            time_list.append(float(time[0]))
            rate_list.append(float(rate[0]))

plt.figure()
plt.plot(time_list, rate_list)
plt.xlabel('Time(sec)')
plt.ylabel('Bandwidth(Mbits/sec)')
plt.grid()
plt.show()