我有一个python脚本,它在raspberry pi 3的开头用一个守护进程启动。
这是我修改过的脚本,之前它运行得很好。 该脚本从RFID阅读器获取卡的ID,然后在本地服务器上发布请求。
我修改了脚本只是为了在CSV文件中写入卡ID和日期。
当我手动运行脚本时,一切运行正常,它会将数据写入CSV并完美无缺。
但是当我重新启动覆盆子时,CSV文件中的写入不起作用。帖子请求有效。
我没有错误,无论如何脚本继续有效。
我不知道发生了什么。
这是我的剧本:
import requests
import binascii
import sys
import time
import subprocess
import Adafruit_PN532 as PN532
import csv
import datetime
duration = 20000
def post_url(uid, duration):
url = 'http://localhost:1339/app=web/uid=%s/duration=%d' % (uid, duration)
requests.post(url)
def get_url(uid, duration):
url = 'http://localhost:1339/app=web/uid=%s/duration=%d' % (uid, duration)
requests.get(url)
# RPI GPIO pins configuration
CS = 18
MOSI = 23
MISO = 24
SCLK = 25
# Create an instance of the PN532 class
pn532 = PN532.PN532(cs=CS, sclk=SCLK, mosi=MOSI, miso=MISO)
# Call beign to initialize communication with the PN532
pn532.begin()
pn532.SAM_configuration()
# Main loop to detect cards and read a block
with open('log.csv', 'a') as log:
while True:
# Check if a card is available to read
uid = pn532.read_passive_target()
# Try again if no card is available
if uid is None:
continue
# Transforming card ui into hex format for comparison against
# registereed uid cards
card_uid = '0x{0}'.format(binascii.hexlify(uid))
if card_uid is not None:
subprocess.call("date")
print('Hello')
writer = csv.writer(log)
data=[card_uid, datetime.datetime.now()]
writer.writerow([data[0], date[1]])
post_url(card_uid, duration)
time.sleep(5)
else:
continue
.sh文件:
DIR=my/path/to/file
DAEMON=$DIR/card_read.py
DAEMON_NAME=card_read
# Add any command line options for your daemon here
DAEMON_OPTS=""
# This next line determines what user the script runs as.
# Root generally not recommended but necessary if you are using the Raspberry Pi GPIO from Python.
DAEMON_USER=root
# The process ID of the script when it runs is stored here:
PIDFILE=/var/run/$DAEMON_NAME.pid
. /lib/lsb/init-functions
do_start () {
log_daemon_msg "Starting system $DAEMON_NAME daemon"
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
log_end_msg $?
}
do_stop () {
log_daemon_msg "Stopping system $DAEMON_NAME daemon"
start-stop-daemon --stop --pidfile $PIDFILE --retry 10
log_end_msg $?
}
case "$1" in
start|stop)
do_${1}
;;
restart|reload|force-reload)
do_stop
do_start
;;
status)
status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
;;
*)
echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
exit 1
;;
esac
exit 0
答案 0 :(得分:0)
不要打开文件一次,请尝试等待,直到有东西要写,然后只在写入期间保持文件打开。这将强制缓冲区刷新到磁盘,允许您tail -f
并实时查看数据。像这样:
while True:
uid = pn532.read_passive_target()
if uid is not None:
record(uid)
time.sleep(5)
def record(uid):
card_uid = '0x{0}'.format(binascii.hexlify(uid))
with open('log.csv', 'a') as log:
writer = csv.writer(log)
writer.writerow([card_uid, datetime.datetime.now()])
post_url(card_uid, duration)