如何在不中断python程序的情况下运行函数?

时间:2015-03-07 15:01:09

标签: multithreading python-2.7

我是python的新手,我正在研究“从网络摄像头寻找心跳”项目,我希望每秒都能将结果(脉冲)添加到csv文件中。你可以在这里看到基础项目:Base project link < / p>

在get_pulse.py中我做了一些改动。总之这是我的功能:

from lib.device import Camera
from lib.processors import findFaceGetPulse
from lib.interface import plotXY, imshow, waitKey,destroyWindow, moveWindow
import numpy as np      
import datetime
import csv
import time
import threading


     def add_csv(self):
            """
            Adds current data to a csv file
            """
            threading.Timer(1.0,add_csv).start()

            bpm = " " + str(int(self.processor.measure_heart.bpm))

            fd = open('msp.csv','a')
            fd.write(bpm)           
            fd.close()

当我运行add_csv函数时,我收到此错误:

Traceback (most recent call last):
  File "get_pulse.py", line 169, in <module>
    App.main_loop()
  File "get_pulse.py", line 164, in main_loop
    self.key_handler()
  File "get_pulse.py", line 135, in key_handler
    self.key_controls[key]()
  File "get_pulse.py", line 65, in add_csv
    threading.Timer(1.0,add_csv).start()
NameError: global name 'add_csv' is not defined     

那么,如何在不中断程序的情况下将此数据附加到文件中?

1 个答案:

答案 0 :(得分:1)

使用

threading.Timer(1.0,self.add_csv).start()