让这段代码在Raspberry Pi上运行。我通过将数据附加到JSON文件来正常工作,但程序会随着文件大小的增加而崩溃。我相信这是因为SD卡的读/写速度太慢了。保存到内存并在一天结束时转储一直很好,但JSON文件不正确。我需要这些文件有双引号而不是单引号,是正确的JSON。任何想法将不胜感激!
import RPi.GPIO as GPIO
import time
import datetime
def program():
import json
global count, pulse_start, pulse_end, pulse_duration, jsondata
ts = time.time()
hourofday = datetime.datetime.fromtimestamp(ts).strftime('%H%M')
st = datetime.datetime.fromtimestamp(ts).strftime('%m-%d-%Y %H:%M:%S')
to = datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')
do = datetime.datetime.fromtimestamp(ts).strftime('%m-%d-%Y')
GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
GPIO.output(TRIG, False)
time.sleep(2.5)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
GPIO.cleanup
#for testing
distance = 1
if distance < 150:
count = count + 0.5
counter = str({"datetime": st, "time": to, "date": do, "Count": "0.5"})
jsonlist = [jsondata, ",", counter]
jsondata = ''.join(jsonlist)
print("Record added memory. There have been ", count, "customers so far today.")
if hourofday == "2359":
import json
with open('counter-' + do + '.json', 'a') as json_file:
jsonlist = ["[", jsondata, "]"]
jsondata = ''.join(jsonlist)
json_file.write(jsondata)
print("File counter-", do, ".json created and saved.")
time.sleep(60)
count = 0
now = datetime.datetime.now()
fulldate = now.date()
jsondata = str({"index": {"_index": "customer-%s" % fulldate, "_type": "json_file"}})
count = 0
flag = True
now = datetime.datetime.now()
fulldate = now.date()
jsondata = str({"index": {"_index": "customer-%s" % fulldate, "_type": "json_file"}})
while flag:
program()
我在文件中输出如下:
[{'index': {'_index': 'customer-2017-12-19', '_type': 'json_file'}},{'date': '12-19-2017', 'Count': '0.5', 'time': '16:34:55', 'datetime': '12-19-2017 16:34:55'},{'date': '12-19-2017', 'Count': '0.5', 'time': '16:34:57', 'datetime': '12-19-2017 16:34:57'},{'date': '12-19-2017', 'Count': '0.5', 'time': '16:35:00', 'datetime': '12-19-2017 16:35:00'}]
因为这是JSON,所以我需要所有单引号都是双引号才能使用。我试图在一个脚本中完成所有这一切,而不必有一个脚本来转换它。