Reputation: 211
I am running a website in Python's Bottle framework and I am using the keyboard listener from pynput package. The listener is stopped when delete key is pressed. I want the listener to stop, when a certain button in HTML file is clicked on as well. I want to write a function in JavaScript which will be executed when the button is clicked on and which will trigger the delete key to be pressed (which will consequently make the listener stop).
I have found many JS functions on the internet which trigger the delete button to be pressed, but in none of those examples did the keyboard listener stop. The listener in Python never recognized those events. Does anyone know a way to write such JS function that will trigger a key to be pressed and that the listener in Python will recognize that the key has been pressed?
EDIT:
Here is a part of my code (the pynput part):
def on_press(key):
try:
k = key.char
except:
k = key.name
print('Key pressed: ' + k)
if k in ['left', 'right', 'up', 'down', 'delete']:
#print('Key pressed: ' + k)
return False
def dobi_smer():
listener = keyboard.Listener(on_press = on_press)
listener.start()
listener.join()
with keyboard.Events() as events:
for event in events:
if event.key == keyboard.Key.left:
return 'L'
elif event.key == keyboard.Key.right:
return 'R'
elif event.key == keyboard.Key.up:
return 'U'
elif event.key == keyboard.Key.down:
return 'D'
elif event.key == keyboard.Key.delete:
return 'X'
It listens to the keyboard until one of the arrows or delete key is pressed.
According to the answer, I have created also created a new page in my website which would simulate the delete key being pressed. Here is the code in Bottle:
@bottle.post("/igraj/prekini/")
def igraj_prekini():
print("bla")
keyboard.press(keyboard.Key.delete)
keyboard.release(keyboard.Key.delete)
I have tried to send this post request with AJAX with the following functions:
function prekini() {$.post("/igraj/prekini/")}
and
function prekini() {$.ajax('/igraj/prekini/', {type: 'POST'})}
but neither of these two functions worked as the page /igraj/prekini/ was never reached. (string "bla" was never printed)
Upvotes: 1
Views: 339
Reputation: 3987
You can create a stop button
in html, and a write javascript function to listen click
in that button. Now, your function works when you clicked
that button
. So, in that function you can write AJAX code to call some url like /stop_pynput
and a /stop_pynput
route in bottle
like your home page /
. And write code that stops pynput
there or call some functions there and return something. So, Now you have to gain skill to solve this problem with my idea, if you already know it then that's best but if you aren't familiar with ajax then try asking it in comment.
Steps to do in list form:
If any queries, then feel free to ask in comment.
Upvotes: 1