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

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

问题描述:

问题是我不能在不停止整个程序的情况下退出while循环。python如何停止无限循环并继续执行其余代码?

当我在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 

错误:

[email protected]:~/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 
+0

用somevar替换“while True”,当你想退出循环时将这个变量改为False – Tamar

+2

没有必要像“免责声明:绝对noob试图解释一个问题”。提出一个适当问题的责任在于你,无论身份如何,并且当我说如果它在那里的时候会显示noobishness,就相信我。无需为此道歉,只需花时间听取和学习。 –

这将做到这一点:

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

谢谢。但是,当我实现你的解决方案时,ctrl + c什么都不做。 while循环继续进行。 – Pytrik

+0

你需要这个代码*代替信号处理程序的东西。 – mdurant

+0

如果我使用此代码,则会出现问题描述中提到的错误。 – Pytrik

enter image description here

正如你可以看到它与@ mdurant的代码一样完美。

+0

当我尝试这个时,它会给出一个错误,我将它添加到问题描述中。 – Pytrik

+0

@mdurant提供的代码完全适合我,请再试一次,看看您的缩进是否正确。 –

+0

绝对不行。 – Pytrik