我正在使用套接字从传感器接收数据。 我想将这些数据记录到一个csv文件中,单击“开始”,然后单击“停止”时停止,每次创建一个包含两个按钮单击之间发送的数据的单独文件时。
我正在Windows的Jupyter笔记本中使用Python 2。我是ipywidget的新手。
这将返回数据:
time_format = '%Y%m%d%H%M%S%f'
def get_latest_data2():
reader = csv.reader(listen_one_line().split('\n'), delimiter=';') #uses socket data
latest = {}
for row in reader:
concat_times=row[0]+row[1]+row[2] # Date + Time + Milliseconds
latest['timestamp']=datetime.strptime(concat_times, time_format)
latest['tag_address']=row[3]
latest['x_coor']=row[4]
latest['y_coor']=row[5]
latest['z_coor']=row[6]
print >> sys.stderr,"get_latest_data is returning coordinates : "+str(latest['x_coor'])+', '+str(latest['y_coor'])+', '+str(latest['z_coor'])
return latest
按钮应该看起来与此类似
import ipywidgets as widgets
dir = './data/'
widgets.ToggleButtons(
options=['Stop','Start'],
description='Control:',
)
#Start should create a new file (with say timestamp name) and start recording data (timestamp,x_coor,y_coor,z_coor)
#Stop should close the file
屏幕截图:https://i.imgur.com/TARlH5n.png
csv文件应该分开。
答案 0 :(得分:0)
这是一种方法
class recorder(object):
def __init__(self,datadir):
self.datadir=datadir
self.datalist=[]
self.startb = widgets.Button(description="Start")
self.startb.on_click(self._on_start_click)
self.stopb = widgets.Button(description="Stop")
self.stopb.on_click(self._on_stop_click)
def thread_f(self):
while self.stop == False:
latest = get_latest_data2()
self.datalist.append(latest)
#print latest
time.sleep(1)
print 'Stopped'
self.list_to_csv()
def list_to_csv(self):
print 'list to csv called'
print self.datalist
def _on_start_click(self,change):
print 'Recording ...'
self.stop = False
self.th = Thread(target=self.thread_f)
self.th.daemon = True
self.th.start()
def _on_stop_click(self,change):
print 'Stopping ...'
self.stop=True
self.th=None
def display_widgets(self):
display(self.startb)
display(self.stopb)
datadir='./data/'
recordinstance = recorder(datadir)
recordinstance.display_widgets()