【问题标题】:python How can I stop an infinite while loop and continue with rest of code?python 如何停止无限循环并继续执行其余代码?
【发布时间】:2017-06-14 20:37:27
【问题描述】:

问题是我不能在不停止整个程序的情况下退出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”替换为while somevar,退出循环时将此变量改为False
  • 不需要诸如“免责声明:绝对菜鸟试图解释问题。”之类的东西。无论身份如何,提出正确问题的责任都在你身上,相信我,当我说noobishness会显示它是否存在时。无需为此道歉,只需花时间倾听和学习。

标签: python while-loop raspbian raspberry-pi3


【解决方案1】:

这样就可以了:

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

【讨论】:

  • 谢谢。但是,当我实施您的解决方案时, ctrl+c 什么也不做。 while 循环继续进行。
  • 您需要此代码而不是信号处理程序的东西。
  • 如果我改用此代码,则会收到问题描述中提到的错误。
  • 啊,这需要在 with picamera.PiCamera() as camera 块内。我怀疑当你离开那个街区时录音会自动停止。
  • 已修复。这是一个缩进问题。我需要使用 4 个空格而不是制表符,因为我正在使用 nano 修改代码(我认为这是原因,不确定)。谢谢。
【解决方案2】:

如您所见,它与@mdurant 的代码完美配合。

【讨论】:

  • 当我尝试这个时它给出了一个错误,我将它添加到问题描述中。
  • @mdurant 提供的代码非常适合我,再试一次,看看你的缩进是否正确。
猜你喜欢
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多