2017-06-14 137 views
2

問題是我不能在不停止整個程序的情況下退出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,就相信我。無需爲此道歉,只需花時間聽取和學習。 –

回答

4

這將做到這一點:

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

-1

enter image description here

正如你可以看到它與@ mdurant的代碼一樣完美。

+0

當我嘗試這個時,它會給出一個錯誤,我將它添加到問題描述中。 – Pytrik

+0

@mdurant提供的代碼完全適合我,請再試一次,看看您的縮進是否正確。 –

+0

絕對不行。 – Pytrik

相關問題