簡體   English   中英

如何停止無限while循環並繼續執行其余代碼?

[英]python How can I stop an infinite while loop and continue with rest of code?

問題是如果不停止整個程序就無法退出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

在此處輸入圖片說明

如您所見,它與@mdurant的代碼完美配合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM