python - Terminate a Python script after a time period
问题描述
My code does capture images every 2 secs. But the problem is it runs endlessly. I need the script to terminate or close at a time period (i.e like terminate or close after 50secs). I tried using sleep() but suspects that doesn't terminate the whole script or closes it, It just puts the script to sleep ! Hope someone could help me with terminating the script after a time period!
My script :
import cv2
import numpy
import time
capture = cv2.VideoCapture(0)
capture.set(3, 640)
capture.set(4, 480)
img_counter = 0
frame_set = []
start_time = time.time()
while True:
ret, frame = capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if time.time() - start_time >= 2:
img_name = "FaceFrame{}.jpg".format(img_counter)
cv2.imwrite(img_name, frame)
print("{} written!".format(img_counter))
start_time = time.time()
img_counter += 1
解决方案
actual_start_time = time.clock()
start_time = time.time()
while ((time.clock() - actual_start_time) < 50):
#do stuff
Alternatively:
actual_start_time = time.clock()
start_time = time.time()
while True:
#do stuff
if (time.clock() - actual_start_time) > 50):
break
推荐阅读
- nlp - 将依赖树转换为 Arc-eager 转换序列
- python - 如何在 python 中使用 cElementTree 为 XML 中的特定节点插入子节点
- css - 如何为屏幕设置媒体查询,例如我无法在开发工具中进行反复试验的围兜
- ios - Swift 中奇怪的保留周期
- javascript - 向同一个电子邮件地址发送多封电子邮件
- php - 如何在php中设置全局链接
- sql-server - 在 SQL Server 上创建数据透视时出错
- google-maps-embed - 使用 Google Maps 网站创建无钥匙嵌入式地图
- postgresql - 创建更新策略的问题
- css - 设置转换后图像的宽度和高度:旋转