我想将命令的结果保存在csv文件中。我现在有这样的代码:
import sys
import os
import time
import datetime
import subprocess
import csv
with open("compteur_data.csv","a") as csvfile:
date = datetime.datetime.today()
wtr=csv.writer(csvfile)
wtr.writerow(['Date/Heure','DATA']) #pillar title
while True:
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
print '..............................', st
sys.stdout.flush()
cmd = 'sdm120c -a 1 -b 2400 -P N -S 2 -j 20 -z 1 /dev/ttyUSB0'
(c_stdin,c_stdout,c_stderr)=os.popen3(cmd,'r')
out=c_stdout.read()
print out
c_stdin.close()
c_stdout.close()
c_stderr.close()
wtr.writerow([date,out])
time.sleep(5)
我的目的是从sdm120c中收集数据,然后将数据保存在csv文件中。在我的python shell上,我可以看到我每5秒保存一次的所有数据,但是当我打开目标csv文件时,什么都没有写进去。也许有人能问我错在哪里?请。
添加一个调用来将缓冲的内容刷新到文件中。这是通过调用csvfile.flush()
实现的:with open("compteur_data.csv","a") as csvfile:
date = datetime.datetime.today()
wtr=csv.writer(csvfile)
wtr.writerow(['Date/Heure','DATA']) #pillar title
while True:
ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
print '..............................', st
sys.stdout.flush()
cmd = 'sdm120c -a 1 -b 2400 -P N -S 2 -j 20 -z 1 /dev/ttyUSB0'
(c_stdin,c_stdout,c_stderr)=os.popen3(cmd,'r')
out=c_stdout.read()
print out
c_stdin.close()
c_stdout.close()
c_stderr.close()
wtr.writerow([date,out])
#New call to flush added below
csvfile.flush()
time.sleep(5)