在 python 中调用超出范围的线程

Calling a thread out of scope in python

我有一个线程被定义为一个程序,它在 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 中的错误,线程在一段时间后挂起。我想定期检查线程是否存在,如果不存在则重新启动它。所以我做了类似

的事情
    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: global name 'dat' is not defined"。我还尝试使用对象名称路径引用线程。但也没有用。

有人可以帮助我如何在范围外启动线程吗?

您似乎想用 self.dat 替换 datdat 仅存在于 __init__ 方法的范围内。我建议阅读 Python 范围规则。