crontab
ファイルに次のコマンドを入れました。
@reboot python3 /home/pi/rpi_camera_surveillance_system.py &
@reboot python3 /home/pi/KestrelPi/PIRkestrellogger.py &
最初のスクリプトは正しく実行されますが、2番目のスクリプトはそうではありません。以下に両方のスクリプトを含めましたが、2番目のスクリプトもテストしましたが、コマンドラインから呼び出すと正常に動作しました。
最初のスクリプト:
# Web streaming example
# Source code from the official PiCamera package
# http://picamera.readthedocs.io/en/latest/recipes2.html#web-streaming
import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server
PAGE="""\
<html>
<head>
<title>Kestrel Camera</title>
</head>
<body>
<center><h1>Kestrel Cam</h1></center>
<center><img src="stream.mjpg" width="640" height="480"></center>
</body>
</html>
"""
class StreamingOutput(object):
def __init__(self):
self.frame = None
self.buffer = io.BytesIO()
self.condition = Condition()
def write(self, buf):
if buf.startswith(b'\xff\xd8'):
# New frame, copy the existing buffer's content and notify all
# clients it's available
self.buffer.truncate()
with self.condition:
self.frame = self.buffer.getvalue()
self.condition.notify_all()
self.buffer.seek(0)
return self.buffer.write(buf)
class StreamingHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(301)
self.send_header('Location', '/index.html')
self.end_headers()
elif self.path == '/index.html':
content = PAGE.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', len(content))
self.end_headers()
self.wfile.write(content)
elif self.path == '/stream.mjpg':
self.send_response(200)
self.send_header('Age', 0)
self.send_header('Cache-Control', 'no-cache, private')
self.send_header('Pragma', 'no-cache')
self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
self.end_headers()
try:
while True:
with output.condition:
output.condition.wait()
frame = output.frame
self.wfile.write(b'--FRAME\r\n')
self.send_header('Content-Type', 'image/jpeg')
self.send_header('Content-Length', len(frame))
self.end_headers()
self.wfile.write(frame)
self.wfile.write(b'\r\n')
except Exception as e:
logging.warning(
'Removed streaming client %s: %s',
self.client_address, str(e))
else:
self.send_error(404)
self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
allow_reuse_address = True
daemon_threads = True
with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
output = StreamingOutput()
#Uncomment the next line to change your Pi's Camera rotation (in degrees)
#camera.rotation = 90
camera.start_recording(output, format='mjpeg')
try:
address = ('', 8000)
server = StreamingServer(address, StreamingHandler)
server.serve_forever()
finally:
camera.stop_recording()
2番目のスクリプト:
# Log motion in Kestrel Box every five seconds in a csv file
import RPi.GPIO as GPIO
import time
import datetime
import csv
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN) #Read output from PIR motion sensor
GPIO.setup(3, GPIO.OUT) #LED output pin
while True:
i=GPIO.input(11)
if i==0: #When output from motion sensor is LOW
print ("No motion",i)
GPIO.output(3, 0) #Turn OFF LED
time.sleep(5)
elif i==1: #When output from motion sensor is HIGH
now = datetime.datetime.now()
GPIO.output(3, 1) #Turn ON LED
with open('bird_log.csv', 'a', newline='') as csvfile:
logwriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
logwriter.writerow([now.strftime("%Y")] + [now.strftime("%d")] + [now.strftime("%m")] + [now.strftime("%H")] + [now.strftime("%M")] + [now.strftime("%S")] + ["motion"])
print ([now.strftime("%Y")] + [now.strftime("%d")] + [now.strftime("%m")] + [now.strftime("%H")] + [now.strftime("%M")] + [now.strftime("%S")] + [ "motion"])
time.sleep(5)
最初のスクリプトに加えて、起動時に2番目のスクリプトをどのように実行できるか疑問に思います。
ベストアンサー1
はじめに:
cron
スクリプトがコマンドPATH
ラインで実行されますが、以下では実行されない場合リソースタイミング質問:
1.PATH
他のポイント:
cron
仕事確かに同じように実行環境対話型シェルで実行されるコマンド。printenv
違いを示すことができます:
$ printenv
...
PATH=/home/pi/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin: etc, etc
...
これでファイルを編集して実行し、出力をファイルにリダイレクトするタスクを作成crontab
します。cron
printenv
* * * * * /usr/bin/printenv > /home/pi/mycronenvironment.txt 2>&1
あなたの中にいるなら、crontab
あなたの中にいるならいいえPATH で 1) PATH を変更するか、2) コマンドのフルパスを使用できます。
2.cron
リソースの可用性を理解できない
@reboot
これは、作業スケジュールをキャッチするためにこの施設を使用するときに最も頻繁に発生します。たとえば、cron
ジョブが起動時に開始され、ネットワークサービスが必要な場合です。ネットワークがまだ利用できない場合、操作は失敗します。そうではないからインタラクティブ、出力(stdout
および/またはstderr
)が表示されず、エラーメッセージまたは警告が失われる可能性があります。
sleep
解決策は通常、コマンドを実行する前に何かを追加することです。たとえば、
@reboot /bin/sleep 20; /path/to/myscript >> /pi/home/myscriptlog.txt 2>&1
cron
起動時に起動し、この行が実行されると、次のコマンドが実行される前に20秒が経過しcron
ます。sleep
これはほぼ常に動作しますが、もちろん不正確リソースがいつ利用できるかわからないからです。あなたの職業がこれを求める場合、またはこれらの不確実性があなたを悩ませている場合、あなたは考慮する必要がありますsystemd
;起動中にシステムリソースの可視性を維持し、できるだけ早く作業を開始できます。
cron
注:デフォルトで実行されているジョブに関するエラーメッセージ/dev/null
この問題は上記のように修正されました。リダイレクトそして「ログファイル」stderr
:stdout
>> /home/pi/cronjoboutput.log 2>&1