I am trying to detect the key pressed by a user in order to reset a variable for my program, a basic application to detect a barcode, which is running inside a While true
I have tried using keyboard
library like in the first solution suggested here
import keyboard # using module keyboard
while True:
if keyboard.is_pressed('q'): # if key 'q' is pressed
print('You Pressed A Key!')
...
but I m getting an error You must be root to use this library on Linux
. I am not sure if that it means is not possible to use this approach in my case because I m ruining the program on Raspberry Pi OS.
I also tried the second approach ( from the same link) using pynput.keyboard
but as the author says, it does not perform well when using inside a loop. the application waits for a key to be pressed.
Edit : More Info
from pyzbar import pyzbar
import datetime
import imutils
import time
from imutils.video import VideoStream
import pika
import json
from pynput.keyboard import Key, Listener
connection = pika.BlockingConnection(
pika.ConnectionParameters(host="----",
virtual_host="----",
credentials=pika.credentials.PlainCredentials(
"---", "---")
))
channel = connection.channel()
channel.queue_declare(queue='barcode_queue')
print("[INFO] Connection Started ...")
vs = VideoStream(usePiCamera=True).start()
print("[INFO] starting video stream...")
time.sleep(2.0)
userWebsocket = None
while True:
# this is what I want to achive
# key = Get the key pressed
# if key == 'q' then userWebsocket = None
frame = vs.read()
frame = imutils.resize(frame, width=400)
barcodes = pyzbar.decode(frame)
for barcode in barcodes:
barcodeData = barcode.data.decode("utf-8")
barcodeType = barcode.type
if barcodeType == 'QRCODE':
decodedBarcode = json.loads(barcodeData)
print(decodedBarcode)
print(decodedBarcode['name'])
userWebsocket = decodedBarcode['id']
else:
print(datetime.datetime.now(), barcodeData, barcodeType)
if (userWebsocket is None):
print("please login before")
else:
sentObj = {"socket": userWebsocket, "barcode": barcodeData}
jsonSentObj = json.dumps(sentObj)
channel.basic_publish(exchange='', routing_key='barcode_queue', body=jsonSentObj)
time.sleep(5)
vs.stop()
What I want to achieve is to "sign-out" the user when he presses a certain key.