Python 3 使用请求的流式视频:循环在哪里?

Python 3 streaming video using requests: where is the loop?

Va运行 Chatterji 发布了 how to use requests to stream video from an IP(以太网)摄像头,需要登录名和密码。这正是我所需要的,也是我在 python 3.4 on windows 7.

中唯一适用于我的相机的东西

然而,他的代码中的循环在哪里?当我 运行 这段代码在 cv2 window 中显示视频时,它会无限地 运行s。但是,该代码缺少 "while True:" 语句,我在搜索中找不到任何帮助。我想将循环移动到更高级别的模块,但我不知道循环在哪里。

换句话说,有人可以重构这段代码,使某处有一条 "while True:" 行吗?这会让我看到循环内的内容和不在循环内的内容。我发现很难遵循请求文档。

Va运行的代码供参考:

import cv2
import requests
import numpy as np

r = requests.get('http://192.168.1.xx/mjpeg.cgi', auth=('user', 'password'), stream=True)
if(r.status_code == 200):
    bytes = bytes()
    for chunk in r.iter_content(chunk_size=1024):
        bytes += chunk
        a = bytes.find(b'\xff\xd8')
        b = bytes.find(b'\xff\xd9')
        if a != -1 and b != -1:
            jpg = bytes[a:b+2]
            bytes = bytes[b+2:]
            i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
            cv2.imshow('i', i)
            if cv2.waitKey(1) == 27:
                exit(0)
else:
    print("Received unexpected status code {}".format(r.status_code))

这样做的动机是我想把东西 "inside the loop" 移动到一个子程序中,调用它 ProcessOneVideoFrame() 然后能够放入更大的程序中:

while True:
    ProcessOneVideoFrame()       
    CheckForInput()
    DoOtherStuff()
    ...

However, where is the loop in his code?

在这一行:

for chunk in r.iter_content(chunk_size=1024):

iter_content 是一个循环直到流为空的生成器。

这里有一些文档:http://docs.python-requests.org/en/latest/api/#requests.Response.iter_content

嗯,stream=True基本上告诉我们总是运行只要接收到等于while True语句的数据。还有一个内部循环,即 François 回答中已经解释过的 for chunk in r.iter_content(chunk_size=1024)