我试图做一个数据记录器,而不是写每分钟只输出一次的串行设备的输出。我需要它在输出上有一个时间戳。到目前为止,我拥有的代码将记录输出,但它会使用设备输出之间的时间戳记来记录空白。当设备输出时,如何只用时间戳写一行?
#!/usr/bin/env python
Log data from serial port
import argparse
import serial
import datetime
import time
import os
timestr = time.strftime("%Y%m%d")
Tstamp = time.strftime("%Y/%m/%d %H:%M ")
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(1)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
outputFile.write(Tstamp + " " + data + '\n')
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")
很抱歉格式不正确,我不确定如何在此处显示它。
答案 0 :(得分:0)
通过添加if x!= ""
并正确缩进,我可以使其正常工作。现在,我只需要对其进行修复即可添加文件而不覆盖它。
#!/usr/bin/env python
# Log data from serial port
import argparse
import serial
import datetime
import time
import os
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-d", "--device", help="device to read from", default="/dev/ttyUSB0")
parser.add_argument("-s", "--speed", help="speed in bps", default=9600, type=int)
args = parser.parse_args()
outputFilePath = os.path.join(os.path.dirname(__file__),
datetime.datetime.now().strftime("%Y-%m-%d") + ".csv")
with serial.Serial(args.device, args.speed) as ser, open(outputFilePath,'w') as outputFile:
print("Logging started. Ctrl-C to stop.")
try:
while True:
time.sleep(1)
x = (ser.read(ser.inWaiting()))
data = x.decode('UTF-8')
if data !="":
outputFile.write(time.strftime("%Y/%m/%d %H:%M ") + " " + data )
outputFile.flush()
except KeyboardInterrupt:
print("Logging stopped")