Search code examples
camerakeystroke

How to stop PiCamera preview on keystroke?


I made a code through python to operate a preview of my PiCamera, I have set the time to 10 seconds, then automatically turns off. However I am unsure how I would be able to have a keystroke to stop the camera and return to the previous screen? At the moment I am able to view for 10 seconds, and nothing else, the usual ctrl-c and various other keys does not work.

How would I be able to integrate a keystroke into the code following to stop the script and return to normal screen?

from picamera import PiCamera
from time import sleep

camera = PiCamera()

camera.start_preview()
sleep(10)
camera.stop_preview()

Solution

  • Subprocess module you can check on the official page:

    https://docs.python.org/2/library/subprocess.html#subprocess.Popen

    A possible way to implement with subprocess.Popen is here on SO:

    Controlling a python script from another script

    Another possibility is to use multiprocesses or multithreading module. For instance creation of a thread can be done and you can take care of an ID :-)

    All the possibility will lead you to learn a bit more of python!

    My better suggestion will be to create easily a thread (https://docs.python.org/3/library/threading.html --> here for python 3), get the ID and leave it run.

    If you want to terminate the camera running, then terminate the thread :-)