python 如何停止无限 while 循环并继续执行其余代码?

标签 python while-loop raspbian raspberry-pi3

问题是我无法在不停止整个程序的情况下退出 while 循环。

当我在 Raspberry Pi 上执行代码时,摄像头开始录制,但是当我想结束视频并按 Ctrl+c 时,整个程序会停止,而不是在 while 循环后继续。我以为信号处理程序会捕获键盘中断,但事实并非如此。

我的代码:

import picamera
import signal
from time import sleep
from subprocess import call

def signal_handler(signal, frame):
        global interrupted
        interrupted = True

signal.signal(signal.SIGINT, signal_handler)

interrupted = False

# Setup the camera
with picamera.PiCamera() as camera:
    camera.resolution = (1640, 922)
    camera.framerate = 30

    # Start recording
    camera.start_recording("pythonVideo.h264")

while True:
        sleep(0.5)
        print("still recording")

        if interrupted:
                print("Ctrl+C pressed")
                camera.stop_recording()
                break

# Stop recording
#camera.stop_recording()

# The camera is now closed.

print("We are going to convert the video.")
# Define the command we want to execute.
command = "MP4Box -add pythonVideo.h264 convertedVideo.mp4 -fps 30"
#Execute command.
call([command], shell=True)
# Video converted.
print("Video converted.")

我尝试过的:

bflag = True
while bflag ==True:
        sleep(0.5)
        print("still recording")

        if interrupted:
                print("Ctrl+C pressed")
                camera.stop_recording()
                bflag = False

错误:

pi@raspberrypi:~/Documents/useThisFolder $ python cookieVideo.py 
still recording
still recording
still recording
still recording
still recording
^Cstill recording
Ctrl+C pressed
Traceback (most recent call last):
  File "cookieVideo.py", line 29, in <module>
    camera.stop_recording()
  File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 1193, in stop_recording
'port %d' % splitter_port)
picamera.exc.PiCameraNotRecording: There is no recording in progress on port 1

最佳答案

这样就可以了:

while True:
    try:
        sleep(0.5)
        print("still recording")
    except KeyboardInterrupt:
        print("Ctrl+C pressed")
        camera.stop_recording()
        break

关于python 如何停止无限 while 循环并继续执行其余代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44554308/

相关文章:

dart - asm/socket.h : No such file or directory cross compiling Dart for Raspberry pi

python - cv2.fillPoly 奇怪的结果

python - 转换字符串参数以发送电子邮件可以帮助我(python)

python - 使用月费计算正确的实际利率

php - jquery和php,加载图片并使用每个图片的src

php - Wordpress 高级自定义字段重复器在循环外显示标题

c - 在 Raspberry PI 上自动运行 C 程序

python - 我可以在 Folium map 上添加一系列标记吗?

python - 为什么它会在调用形状函数中调出局部变量 'size'?

linux - 在拍摄照片之前调整网络摄像头设置(v4l2 和 fswebcam)