安装pandas、numpy、matplotlib后Python代码报退出码3求助
问题:Python绘图代码报错Process ended with exit code 3,移除绘图代码则正常运行
我编程经验不多,当前开发的项目是通过USB将嵌入式系统的数据传输至Thonny并存储为CSV文件。尝试用matplotlib、pandas、numpy绘图时,发现未安装这些库,用Thonny内置包管理器安装后,运行程序持续出现“Process ended with exit code 3”错误;移除绘图相关代码及导入语句后,程序可正常运行并写入CSV文件。尝试重装库但无法安装至最新稳定版本,附上代码求助:
import serial import csv from time import time as current_time from time import sleep import pandas as pd import numpy as np import matplotlib as plt ser = serial.Serial() ser.baudrate = 115200 ser.port = "COM5" db_list = [] print("Type CTRL + C to exit. (may take 5 seconds)") ser.open() start_time = current_time() for i in range(10): microbitdata = str(ser.readline()) decibel_level = microbitdata[2:] decibel_level = decibel_level.replace(" ","")#removes any spaces from the data decibel_level = decibel_level.replace("'","")#removes an opostrophies decibel_level = decibel_level.replace("\\r\\n","")# replace \r\n with a blank space decibel_level = decibel_level.replace("\\r","") #replace \r with nothing decibel_level = decibel_level.replace("\\n","") #replace \n with nothing sleep(0.1)#break between data being added elapsed_time = round(current_time() - start_time) print("Elapsed time:", elapsed_time,"/db level:", decibel_level) sleep(1) # Pauses the loop for 1 second decibel_level = int(decibel_level) db_list.append(decibel_level) safe = decibel_level <= 70 potential_damage = 71<= decibel_level <= 90 risk_of_hearing_loss = 91<= decibel_level <=119 immediate_harm = decibel_level >= 120 path = "Sound_level_data.csv" #naming the file name f = open(path, "a", newline='')#appends at the end of each line writer = csv.writer(f) writer.writerow([elapsed_time,decibel_level]) f.close() #calc the trendline and plots the graph csv = pd.read_csv('Sound_level_data.csv') data = csv[['Time', 'Sound Level']] x = data['elapsed_time'] y = data['decibel_level'] plt.scatter(x, y) z = np.polyfit(x, y, 1) p = np.poly1d(z) plt.plot(x,p(x),"r--") plt.xlabel('db Level') plt.ylabel('Time') print("The slope is", z[0]) print("The intercept is", z[1]) print("The equation of the line is y="+str(round(z[0],2))+"x+"+str(round(z[1],2))) plt.savefig("graph.png") plt.show()
问题排查与解决方法
1. 修正matplotlib导入方式
原代码中import matplotlib as plt错误,matplotlib的绘图方法在pyplot子模块中,正确导入应为:
import matplotlib.pyplot as plt
2. 解决CSV列名不匹配问题
你写入CSV时没有添加表头,但读取时用了不存在的列名Time、Sound Level,后续又调用elapsed_time、decibel_level,会触发KeyError。修改写入逻辑,首次创建文件时添加表头:
import os # 需要导入os模块 path = "Sound_level_data.csv" # 首次创建文件时写入表头 if not os.path.exists(path): with open(path, "w", newline='') as f: writer = csv.writer(f) writer.writerow(['elapsed_time', 'decibel_level']) # 追加数据 with open(path, "a", newline='') as f: writer = csv.writer(f) writer.writerow([elapsed_time, decibel_level])
读取时使用正确的列名:
# 不要用csv作为变量名,会覆盖内置的csv模块 df = pd.read_csv('Sound_level_data.csv') x = df['elapsed_time'] y = df['decibel_level']
3. 增加串口数据异常处理
串口数据可能存在格式异常,直接转int会报错,添加异常捕获:
try: decibel_level = int(decibel_level) except ValueError: print(f"无效数据:{microbitdata}") continue # 跳过无效数据,继续循环
4. 修复绘图标签错误
x轴是时间,y轴是分贝值,原代码标签写反了:
plt.xlabel('时间(秒)') plt.ylabel('分贝值(db)')
5. 解决Thonny库安装问题
如果Thonny内置包管理器无法安装最新版,打开Thonny的「工具」→「打开系统shell」,运行以下命令强制升级:
pip install matplotlib pandas numpy --upgrade
修改后的完整代码
import serial import csv import os from time import time as current_time from time import sleep import pandas as pd import numpy as np import matplotlib.pyplot as plt ser = serial.Serial() ser.baudrate = 115200 ser.port = "COM5" db_list = [] print("Type CTRL + C to exit. (may take 5 seconds)") ser.open() start_time = current_time() path = "Sound_level_data.csv" # 首次创建文件时写入表头 if not os.path.exists(path): with open(path, "w", newline='') as f: writer = csv.writer(f) writer.writerow(['elapsed_time', 'decibel_level']) for i in range(10): microbitdata = str(ser.readline()) decibel_level = microbitdata[2:] # 清理数据 decibel_level = decibel_level.replace(" ","").replace("'","") decibel_level = decibel_level.replace("\\r\\n","").replace("\\r","").replace("\\n","") sleep(0.1) elapsed_time = round(current_time() - start_time) print("Elapsed time:", elapsed_time,"/db level:", decibel_level) # 异常处理:跳过无效数据 try: decibel_level = int(decibel_level) except ValueError: print(f"跳过无效数据:{microbitdata}") sleep(1) continue db_list.append(decibel_level) # 追加数据到CSV with open(path, "a", newline='') as f: writer = csv.writer(f) writer.writerow([elapsed_time, decibel_level]) sleep(1) # 绘图部分 df = pd.read_csv('Sound_level_data.csv') x = df['elapsed_time'] y = df['decibel_level'] plt.scatter(x, y) # 生成趋势线 z = np.polyfit(x, y, 1) p = np.poly1d(z) plt.plot(x, p(x), "r--") plt.xlabel('时间(秒)') plt.ylabel('分贝值(db)') print(f"斜率:{z[0]}") print(f"截距:{z[1]}") print(f"趋势线方程:y={round(z[0],2)}x+{round(z[1],2)}") plt.savefig("graph.png") plt.show()
内容的提问来源于stack exchange,提问作者GavinMC
相关产品推荐
相关产品推荐

