Python线程 - 从另一个函数停止线程

时间:2015-03-19 20:08:53

标签: python multithreading

我已经开始在python中使用线程,看了很多教程后我终于在我的项目中使用了线程 - 但是我没有找到任何线程从另一个函数停止的示例。所以我可以启动线程,它工作正常,CSV写得正确,但我不能阻止它。我从stop函数中得到以下错误:

  

文件“./blackboxv1.1.py”,第162行,在stop_csv_logging中       csv_thread.join()
  NameError:未定义全局名称'csv_thread'

我已经附加了我的代码,它只是来自更大一点代码的片段,但我觉得应该是相关的一切都在那里。该代码基本上将GPS数据写入CSV文件以记录GPS和加速度计数据,从调用启动和停止功能的菜单调用它。

每个功能中的这一位都可以通过LCD板上的按钮捕捉按键,并且工作正常。

sleep(0.5)
  while 1:
        if lcd.is_pressed(0):
           break
        else:

我对Python很新,所以这是一条陡峭的曲线。

class WriteCSV:
    def __init__(self):
            self._running = True

        def terminate(self):
            self._running = False

    def run(self):
            # create unique filename based on date/time
            new_file = time.strftime("%Y%m%d-%H%M%S.csv")
            file_path = "/home/pi/scripts/gps/log_data/"
            new_filename = file_path + new_file
            # Set headers for csv
            headers = ['TimeStamp', 'Speed', 'Lat', 'Lon', 'Alt', 'Climb', 'Acc_X', 'Accl_Y']
            # needed to get accl data
            accel = lsm.readAccelerationsG()
            # create file and set headers then close
            outfile = open(new_filename, 'a+')
            writer = csv.writer(outfile)
            writer.writerow(headers)
            outfile.close()
        while self._running:
                 # reopen existing file
                 outfile = open(new_filename, 'a+')
                 writer = csv.writer(outfile)
                 # unique timestamp needed for each row
                 time_stamp = time.strftime("%Y%m%d-%H%M%S")
                 # need to round down the g force numbers
                 accel.x = round(accel.x,1)
                 accel.y = round(accel.y,1)
                 # Set Row
                 row = [time_stamp, gpsd.fix.speed, gpsd.fix.latitude, gpsd.fix.longitude, gpsd.fix.altitude, gpsd.fix.climb, accel.x, accel.y]
                 # Write Row
                 writer.writerow(row)
                 # Close file
                 outfile.close()
                 # set sleep of 1 sec
                 sleep(1)


#========================================================
# Start CSV Logging
#========================================================

def start_csv_logging():
# create an instance of class WriteCSV
# create a thread using the instance
# then start the thread
  sleep(0.5)
  while 1:
        if lcd.is_pressed(0):
           break
        else:
       global csv_log
       csv_log = WriteCSV() 
       # create the thread and start run()
       csv_thread = threading.Thread(target=csv_log.run) 
       # start it up
       csv_thread.start()
       lcd.clear()
       lcd.message("Starting Log ..")
       sleep(2)
       lcd.clear()
       lcd.message("Logging!")
       break    

#========================================================
# Stop CSV Logging
#========================================================

def stop_csv_logging():
  sleep(0.5)
  while 1:
        if lcd.is_pressed(0):
           break
        else:
       # Signal termination
       csv_log.terminate()
       csv_thread.join()      
       # Wait for termination
       lcd.clear()
           lcd.message("Stopping ....")
       sleep(2)
       lcd.clear()
       lcd.message("Log Stopped!")
       sleep(2)
       break    
#========================================================

0 个答案:

没有答案