错误:“分配前引用了局部变量‘myData’”
Posted
技术标签:
【中文标题】错误:“分配前引用了局部变量‘myData’”【英文标题】:Error: "local variable 'myData' referenced before assignment" 【发布时间】:2020-09-22 21:56:24 【问题描述】:晚上好,
我是 python 新手。我在尝试开发来自 LIDAR 传感器的实时绘图数据时正在学习教程。我收到错误“UnboundLocalError: local variable 'myData' referenced before assignment”有人知道如何解决这个问题吗?
import pyqtgraph as pg
import sys # We need sys so that we can pass argv to QApplication
import os
import serial
import csv
import numpy as np
from datetime import datetime
from matplotlib import pyplot as plt
from matplotlib import style
from PyQt5 import QtWidgets, uic, QtCore
from pyqtgraph import PlotWidget, plot
arduinoSerialData = serial.Serial('com3', 9600)
NameofCSV = 'data2.csv'
style.use('ggplot')
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.graphWidget = pg.PlotWidget()
self.setCentralWidget(self.graphWidget)
if (arduinoSerialData.inWaiting()>0):
myData = arduinoSerialData.readline()
xn = datetime.now()
Time = xn.strftime('%H%M%S')
with open(NameofCSV, 'a', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=' ')
info = (float(myData), float(Time))
writer.writerow(info)
# print(float(myData), Time)
x1,y1 = np.loadtxt(NameofCSV, unpack = True, delimiter = ' ')
self.x = x1
self.y = y1
self.graphWidget.setBackground('w')
pen = pg.mkPen(color=(255, 0, 0))
self.data_line = self.graphWidget.plot(self.y, self.x, pen=pen)
# ... init continued ...
self.timer = QtCore.QTimer()
self.timer.setInterval(50)
self.timer.timeout.connect(self.update_plot_data)
self.timer.start()
def update_plot_data(self):
self.x = self.x[1:] # Remove the first y element.
self.x.append(self.x[-1] + 1) # Add a new value 1 higher than the last.
self.y = self.y[1:] # Remove the first
self.y.append(self.y) # Add a new random value.
self.data_line.setData(self.x, self.y) # Update the data.
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
【问题讨论】:
【参考方案1】:所以,myData
只在这个块中被初始化:
if (arduinoSerialData.inWaiting()>0):
myData = arduinoSerialData.readline()
如果 if
子句的计算结果不为 True,它将跳过它,稍后您将使用 myData
而不对其进行初始化:info = (float(myData), float(Time))
您可以在顶部将 myData 初始化为某个起始值,或者确保将其设置为某个值的代码始终在使用其值之前运行。
编码愉快!
【讨论】:
以上是关于错误:“分配前引用了局部变量‘myData’”的主要内容,如果未能解决你的问题,请参考以下文章