【问题标题】:Downloading just one image from a server that keeps sending them从不断发送它们的服务器仅下载一张图像
【发布时间】:2015-01-24 22:14:56
【问题描述】:

有一个服务器从闭路电视发送图像。数据如下所示:

--BoundaryString
Content-type: image/jpeg
Content-Length:       15839
... first image in binary...
--BoundaryString
Content-type: image/jpeg
Content-Length:       15895
... second image in binary...

等等(它会无限期地继续下去)。我正在尝试 pyCurl 只获取一张图片,如下所示:

curl = pycurl.Curl()
curl.setopt(curl.URL, 'http://localhost:8080')
with open('image.jpg', 'w') as fd:
    curl.setopt(curl.WRITEFUNCTION, fd.write)
    curl.perform()

但它不会在一张图像后停止,而是继续从服务器读取。有没有办法告诉 curl 在一个部分之后停止?

或者,我可以只使用一个套接字并自己实现一个简单的 GET /。这不是问题。但是我想知道是否可以在这种情况下使用 pyCurl,我也想知道这是什么,因为它对我来说看起来不像是正确的多部分消息。

服务器是一种叫做“motion”的东西(Linux 的视频运动检测守护程序)。

谢谢。

【问题讨论】:

    标签: python libcurl pycurl


    【解决方案1】:

    这是一些适合我的代码。 (蟒蛇2) 这将为您获取服务器发送的所有图像。如果您只需要一张,请在保存图片后sys.exit(0)

    from functools import partial
    import socket
    
    
    def readline(s):
        fx = partial(s.recv, 1)
        ret = [x for x in iter(fx, '\n')]
        return ''.join(ret)
    
    
    def main():
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(("127.0.0.1", 8080))
    
        while True:
            line = readline(s)
            if line.rstrip('\r') == '--BoundaryString':
                content_type = readline(s)
                length = int(readline(s).rstrip('\r').split()[-1])
                _ = readline(s)  # we skip an empty line
                image = ''
                while length:
                    data = s.recv(length)  # here is receiving only 1375 bytes even if you tell it more
                    length -= len(data)  # so we decrement and retry
                    image += data
                # print repr(image[:20])  # was for debug
                # TODO --> open a file and save the image
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多