Home > Software engineering >  Python FLASK Return KeyboardIntrupt
Python FLASK Return KeyboardIntrupt

Time:09-27

I have a rout for Flask that will once a button is clicked it executes another python script "Voice_Recorder.py" however. This script starts recording a wav file but to stop recording the and save the file I need to either pass though a keyboardinterrupt or to the Voice_Recorder.py file. How can you passthrough a keyboardinterrupt from the front end in flask?

**PY FILE**
  **@app.route('/record/',methods=['POST'])
  def record():
    import Voice_Recorder.py  
    return'done'** 

****HTML FILE**
  **center><button> <a href="/record/">Start recoring!</a></button></center>****    

CodePudding user response:

Short answer: You cannot. Flask is on the Backend and the Frontend is running in a browser, potentially on any other PC / Mobile etc.

Also, it seems that importing the script **Voice_Recorder.py ** is a blocking operation - that blocks the dev server totally and would prevent you from sending any commands to it. In real world production servers (gunicorn etc) that does not happen, but then there are running several processes so one proce is stuck running your script, while the others cannot prevent it from doing so.

Suggestion:

Your Flask Server should have two routes record and stop_record, your website needs two buttons to expose that. Record should probably start the voice_recorder using subprocess ( How to execute a program or call a system command? ) while stop_record needs to send a keyboard command to that script OR write a text file somewhere that Voice Commands.py listens for and shuts down on its own.

There are other solutions, but given the level of your question I am fairly sure they are too complicated for now.

CodePudding user response:

You can make a use of something called pynput :

  pip install pynput

This will help to detect any key press. “pynput.keyboard” contains classes for controlling and monitoring the keyboard.

For example for pressing "Space bar"

from pynput.keyboard import Key, Controller

keyboard = Controller()

# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)

Ful doc here

  • Related