使用线程的Python UnboundLocalError

时间:2015-07-05 10:24:50

标签: python multithreading raspberry-pi

我试图在Raspberry Pi2上使用接近传感器,我希望每个传感器都在不同的线程上运行,因此我使用了线程模块。如果我只使用2个线程,一切正常,但是当我尝试运行3个线程时,我收到此错误:

  

线程Thread-3中的异常:   Traceback(最近一次调用最后一次):    文件" /usr/lib/python2.7/threading.py",第552行,在__bootstrap_inner中      self.run()    文件" /usr/lib/python2.7/threading.py" ;,第505行,运行中      self .__ target(* self .__ args,** self .__ kwargs)    文件" range_sensor.py",第52行,计量      pulse_duration = pulse_end - pulse_start   UnboundLocalError:局部变量' pulse_start'在分配前引用

这是代码,我不明白什么是错的

tuples = [(1, 'Bagno Cla', 'Toilet paper', 23, 24),
          (1, 'Bagno Ladispe', 'Trash', 25, 8),
          (2,'Bagno inventato', 'Soap', 16,20)]

def measure(bathroomFloor, bathroomId, item, TRIG, ECHO):
#     getting raspberry and sensors ready
    GPIO.setup(TRIG,GPIO.OUT)
    GPIO.setup(ECHO,GPIO.IN)
    GPIO.output(TRIG, False)
    print "Waiting For Sensor To Settle"
    time.sleep(2)

    T=60
    while True:     
        print "Distance Measurement In Progress"
        time.sleep(5) #sampling period    
        GPIO.output(TRIG, True) 
        time.sleep(0.00001)
        GPIO.output(TRIG, False)

        while GPIO.input(ECHO)==0:
            pulse_start = time.time()
        while GPIO.input(ECHO)==1:
            pulse_end = time.time()

        pulse_duration = pulse_end - pulse_start
        distance = pulse_duration * 17150
        distance = round(distance, 2)
        print "Measured distance in "+bathroomId+":",distance,"cm"
        print "Time of measure in "+bathroomId+":",time.strftime("%H:%M")

GPIO.cleanup()
return


# this is the part of code that launches each thread
try: #launching threads
    i = 0
    while i < len(tuples):
    t = threading.Thread(target=measure, args=tuples[i])
    t.start();
    i+=1

except:
    print "Error: unable to start thread"

1 个答案:

答案 0 :(得分:1)

你应该总是尝试&amp;减少一个例子到最小的工作。然后很清楚会发生什么:

while True
    if False: # not reached
        pulse_start = time.time()
    else:
        pulse_end = time.time()
    print pulse_end - pulse_start # undbound local error!

这与线程无关,但由于传感器串扰,GPIO的状态可能不同,因此在使用之前不要定义puse_start。通常的解决方法是预先设置一个值 - 要么是有用的,要么是哨兵值,例如: None

pulse_start = None
pulse_end = None    
while True:
   if <condition>:
      pulse_start = time.time()
   else:
      pulse_end = time.time()
   if pulse_start is not None and pulse_end is not None:
      print "length", pulse_end - pulse_start
      pulse_end = None # reset pulse_end to prevent printing out a negative length if you started with the second execution path