一段时间后无法连续保存和更新.CSV文件

时间:2013-01-16 21:31:20

标签: python csv collections export-to-csv

我写了一个小程序,每个小步骤从两个设备读取值,然后将其保存到.csv文件中。我希望在每个点的每个集合之后更新和保存文件,以便在PC崩溃或发生其他问题时不会发生数据丢失。为此,我打开文件(ab模式),使用写行并在循环中关闭文件。收集之间的时间约为1分钟。这很安静,但问题是在数据收集5-6小时后,它停止保存到.csv文件,并且没有出现任何错误,代码继续运行,图表正在更新,没有发生任何事情,但打开.csv文件显示数据丢失。我想知道我使用的代码是否有问题。我也不应该从这个运行一个子进程来进行实时绘图,但我不认为它会导致问题...我也添加了这些代码行。

##Initial file declaration and header
with open(filename,'wb') as wdata:
     savefile=csv.writer(wdata,dialect='excel')
     savefile.writerow(['System time','Time from Start(s)','Weight(g)','uS/cm','uS','Measured degC','%/C','Ideal degC','/cm'])

##Open Plotting Subprocess
 draw=subprocess.Popen('TriPlot.py',shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)
##data collection loop
while True:
   Collect Data x and y
   Waits for data about 60 seconds, no sleep or pause commoand used, pyserial inteface is used.
   ## Send Data to subprocess 
   draw.stdin.write('%d\n' % tnow)
   draw.stdin.write('%d\n' % s_w)
   draw.stdin.write('%d\n' % tnow)
   draw.stdin.write('%d\n' % float(s_c[5]))

   ##Saving data Section 
   wdata=open(filename,'ab')
   savefile=csv.writer(wdata,dialect='excel')
   savefile.writerow([tcurrent,tnow,s_w,s_c[5],s_c[7],s_c[9],s_c[11],s_c[13],s_c[15]])
   wdata.close()

P.S此代码对未显示的代码使用以下包。 pyserial,csv,os,subprocess,tkinter,string,numpy,time和wx。

1 个答案:

答案 0 :(得分:1)

如果draw.stdin.write()阻止,则可能意味着您没有及时使用draw.stdout。由于完整的OS管道缓冲区,文档警告死锁。

如果您不需要输出,可以将stdout=devnull设置为devnull = open(os.devnull, 'wb'),否则有几种方法可以在不阻塞代码的情况下读取输出:threads,select,tempfile.TemoraryFile。< / p>