Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:在按键上关闭一个循环_Python_Loops_Security_Raspberry Pi_Exit - Fatal编程技术网

Python:在按键上关闭一个循环

Python:在按键上关闭一个循环,python,loops,security,raspberry-pi,exit,Python,Loops,Security,Raspberry Pi,Exit,我正在用树莓皮制作一个运动检测安全摄像头 代码工作正常,但我希望设备在启动时运行我的python代码,并在我按下某个键时关闭程序。到目前为止,程序运行但不会退出循环,因此我无法进入raspberry pi桌面(我的解决方法是关闭设备,手动移除摄像头,重新打开设备,因为没有检测到摄像头,摄像头会将代码退出桌面……我知道效率非常低!) 基本上,这段代码是为了从连接到监视器、键盘等的pi运行程序而编写的。我只想把它插到某个地方,让它为相机配备武器。然后,在我回到家(工作、度假等)后,我想插入键盘,按一

我正在用树莓皮制作一个运动检测安全摄像头

代码工作正常,但我希望设备在启动时运行我的python代码,并在我按下某个键时关闭程序。到目前为止,程序运行但不会退出循环,因此我无法进入raspberry pi桌面(我的解决方法是关闭设备,手动移除摄像头,重新打开设备,因为没有检测到摄像头,摄像头会将代码退出桌面……我知道效率非常低!)

基本上,这段代码是为了从连接到监视器、键盘等的pi运行程序而编写的。我只想把它插到某个地方,让它为相机配备武器。然后,在我回到家(工作、度假等)后,我想插入键盘,按一下键退出程序,安全关机,并在我将其连接到显示器时能够查看任何安全事件

脚本代码:

from gpiozero import MotionSensor
from picamera import PiCamera
from datetime import datetime

camera = PiCamera()
pir = MotionSensor(4)
while True:
    pir.wait_for_motion()
    filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")
    camera.start_recording(filename)
    pir.wait_for_no_motion()
    camera.stop_recording()

可以在运行脚本的命令行窗口中使用Ctrl+C停止程序执行

如果仍要执行某些处理,请将
while
循环包装在
try
块中,如下所示:

try:
    while True:
        pir.wait_for_motion()
        filename = datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")
        camera.start_recording(filename)
        pir.wait_for_no_motion()
        camera.stop_recording()
except KeyboardInterrupt:
    pass

# Continue your code here

如果您想选择停止程序的键(Ctrl+C除外)和/或在操作系统中的任何位置按下键时停止程序,我建议您使用该库。

如果input()=='':break
?@Shiva不起作用,
input
正在阻塞。哦。。。明白了
signal.signal
也许?您尝试过这个:而且,我在启动时(代码运行时)看到的只是一个黑屏。cmd-C不会导致键盘中断或至少不会退出桌面。这很有效!非常感谢。不幸的是,Raspberry pi没有正确加载脚本,因为我刚刚得到一个黑屏。我会坚持下去的。