我有一个线程,它被定义为在一个程序中连续读取串行数据,并在wxpython中运行UI。
dat = Thread(target=receiving, args=(self.ser,))
它调用的方法"receiving"在一个无限循环中运行
def receiving(ser):
global last_received
buffer = ''
while True:
date = datetime.date.today().strftime('%d%m%Y')
filename1 = str(date) + ".csv"
while date == datetime.date.today().strftime('%d%m%Y'):
buffer = buffer + ser.read(ser.inWaiting())
if 'n' in buffer:
lines = buffer.split('n')
if lines[-2]:
last_received = lines[-2]
buffer = lines[-1]
print_data =[time.strftime( "%H:%M:%S"), last_received]
try:
with open(filename1, 'a') as fob:
writ = csv.writer(fob, delimiter = ',')
writ.writerow(print_data)
fob.flush()
except ValueError:
with open('errors.log','a') as log:
log.write('CSV file writing failed ' + time.strftime("%H:%M:%S")+' on '+datetime.date.today().strftime('%d/%m/%Y')+'n')
log.close()
参数定义为
class SerialData(object):
def __init__(self, init=50):
try:
serial_list = serialenum.enumerate()
self.ser = ser = serial.Serial(
port=serial_list[0],
baudrate=9600,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=None,
xonxoff=0,
rtscts=0,
interCharTimeout=None
)
except serial.serialutil.SerialException:
# no serial connection
self.ser = None
else:
dat = Thread(target=receiving, args=(self.ser,))
if not dat.is_alive:
dat.start()
def next(self):
if not self.ser:
# return anything so we can test when Serial Device isn't connected
return 'NoC'
# return a float value or try a few times until we get one
for i in range(40):
raw_line = last_received
try:
return float(raw_line.strip())
time.sleep(0.1)
except ValueError:
# print 'Not Connected',raw_line
time.sleep(0.1)
return 0
由于Ubuntu 14.04中的一个bug,线程在一段时间后会挂起。我想定期检查线程是否活着,如果不是,就重新启动它。所以我输入了
def on_timer(self):
self.text.SetLabel(str(mul_factor*self.datagen.next()))
if not dat.is_alive():
dat.start()
wx.CallLater(1, self.on_timer)
每秒运行一次以更新UI中的数据,但也需要检查线程是否未停止。但这给了我一个错误说"NameError:全局名称'dat'未定义"。我还尝试使用对象名称路径引用线程。但也没起作用。
有人可以帮助我,我如何才能启动线程超出范围?
您似乎想用self.dat
替换dat
。dat
只存在于__init__
方法的范围内。我建议阅读Python的作用域规则。