I have a Python Simple HTTP server running on a Raspberry Pi, using openCV, I am using this code below to serve a video stream from a webcam over ngrok. I want to ensure it stays running remotely, as I have had it lock-up a few times on me and I need to manually restart it. I am not sure of the reason it periodically fails as I am running the script at startup and can't seem to reproduce the error when I run it from the console.
How can I ensure the HTTP server is running? The docs don't seem to cover this, so maybe it's more of a Linux question?
Here is the working code:
import http.server
import socketserver
import cv2
import time
PORT = 8000
cap = cv2.VideoCapture(0)
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith('/image'):
self.send_response(200)
self.send_header("Content-type", "image/jpeg")
self.end_headers()
ret, frame = cap.read()
_, jpg = cv2.imencode(".jpg", frame)
self.wfile.write(jpg)
else:
self.send_response(404)
myserver = socketserver.TCPServer(("", PORT), MyHandler)
with myserver as httpd:
print("Serving at port ", PORT)
try:
httpd.serve_forever()
except:
pass
My plan is to run this script in parallel:
while True:
serverActive = #someway of confirming server is active (how can I do this?)
if serverActive = False
try:
#attempt to restart server
startServer = subprocess.Popen(["/home/pi/Desktop/startServer.py"], stdin=subprocess.PIPE)
except:
pass
time.sleep(5000)