#python #django #multithreading
Вопрос:
Я пытаюсь переделать проект, основанный на репозитории github, который я нашел некоторое время назад. Когда я пытаюсь запустить авторский код, я получаю сообщение»В потоке» Поток «нет текущего цикла событий».
Я просмотрел в Интернете несколько вопросов stackoverflow, в которых была та же проблема, с которой я сталкиваюсь, но ни один из их кода не похож на мой. Все они использовали пакет Asyncio, в то время как я выбрал пакет с потоковой передачей.
Вот код файла python, в котором возникает ошибка:
import base64
import cv2
import time
from threading import Thread
import RPi.GPIO as GPIO
import collect
import visit
import os
#import save
#from pymongo import MongoClient
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(27, GPIO.OUT)
class Stream(Thread):
def __init__(self):
self.flag = [False]
self.capture_flag = [False]
#self.ws = ws
self.clients = []
Thread.__init__(self, name=Stream.__name__)
def run(self):
self.camera = cv2.VideoCapture(0)
prev_input = 1
#mongo_db = MongoClient('localhost',27017)
#db = mongo_db.smartbell.visitors
while True:
# Read camera and get frame
rval, frame = self.camera.read()
if frame is None:
self.camera.release()
self.camera = cv2.VideoCapture(0)
continue
# Send camera stream to web
if self.flag[0]:
rvel, jpeg = cv2.imencode('.jpg', frame)
encode_string = base64.b64encode(jpeg)
for client in self.clients:
client.write_message(encode_string)
# A visitor pushes button
but = GPIO.input(17)
if(not prev_input and but):
# It affects dlib speed. If frame size is small, dlib would be faster than normal size frame
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
visit.visit(small_frame)
for client in self.clients:
client.write_message("log")
prev_input = but
time.sleep(0.05)
# Click makephotos on web browser
if self.capture_flag[0] == True:
enough_image = collect.make_photo(frame)
if enough_image == "success":
print("Success to register")
else:
print("Fail to register")
for client in self.clients:
client.write_message(enough_image)
self.capture_flag[0] = False
self.camera.release()
def change_capture_flag(self):
self.capture_flag[0] = True
def change_socket_flag(self):
self.flag[0] = not self.flag[0]
def add_client(self, newclient):
self.clients.append(newclient)
def remove_client(self, client):
self.clients.remove(client)
Ошибка:
Exception in thread Stream:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/home/pi/security-recognizer/python/videostream.py", line 55, in run
client.write_message(encode_string)
File "/home/pi/.virtualenvs/pfe/lib/python3.7/site-packages/tornado/websocket.py", line 340, in write_message
return self.ws_connection.write_message(message, binary=binary)
File "/home/pi/.virtualenvs/pfe/lib/python3.7/site-packages/tornado/websocket.py", line 1096, in write_message
fut = self._write_frame(True, opcode, message, flags=flags)
File "/home/pi/.virtualenvs/pfe/lib/python3.7/site-packages/tornado/websocket.py", line 1073, in _write_frame
return self.stream.write(frame)
File "/home/pi/.virtualenvs/pfe/lib/python3.7/site-packages/tornado/iostream.py", line 540, in write
future = Future() # type: Future[None]
File "/usr/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
% threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Stream'.