【问题标题】:python program freezes after client connects客户端连接后python程序冻结
【发布时间】:2016-10-15 06:59:57
【问题描述】:

我有这个 python 程序,它使用烧瓶进行视频流(独立 JPEG 图片序列)。我知道我应该先自己调试它,但是一旦客户端连接 index.html 只显示损坏的图像图标并且计算机冻结。 我试过了-

  • 在运行良好的 linux 上运行它。
  • 禁用或启用线程,但没有效果。

编辑 2

它可以在 Linux 上运行,因为它安装了 python 2.7。在 python 3 中它没有显示任何错误但不起作用。在四个系统(windows 和 linux)上尝试过,似乎是一个兼容性问题,因为它在所有使用 python 3 的计算机上都失败了,但在 python 2 上没有。如何使它在 python 3 中工作?

edit 1 : 通过在gen() 的循环内添加time.sleep(1) 解决了冻结问题,但浏览器中仍然没有输出。在chrome 开发者工具中记录了网络活动。这是一个屏幕截图 -

代码如下:

app.py(服务器)

#!/usr/bin/env python
from flask import Flask, render_template, Response

# emulated camera
from camera import Camera

app = Flask(__name__)


@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')


def gen(camera):
    """Video streaming generator function."""
    while True:
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')


@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(Camera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False, threaded=False)

camera.py

from time import time
class Camera(object):
    """An emulated camera implementation that streams a repeated sequence of
    files 1.jpg, 2.jpg and 3.jpg at a rate of one frame per second."""

    def __init__(self):
        self.frames = [open(f + '.jpg', 'rb').read() for f in ['1', '2', '3']]

    def get_frame(self):
        return self.frames[int(time()) % 3]

index.py(客户端)

<html>
  <head>
    <title>Video Streaming Demonstration</title>
  </head>
  <body>
    <h1>Video Streaming Demonstration</h1>
    <img src="{{ url_for('video_feed') }}">
  </body>
</html>

正如我已经提到的,我不能使用调试器,因为整个计算机会立即冻结。python 版本 - 3.5 和 os - windows 10。
我该如何修复它?

【问题讨论】:

  • 尝试将while True 替换为for i in range(10) 进行调试。那它还结冰吗?另外,如果您每秒流式传输一帧,每帧之后不应该有一个time.sleep(1) 吗?
  • @zvone 它现在没有冻结,谢谢,但仍然没有输出。只是一个损坏的图像图标。
  • @zvone 还添加了 time.sleep(1) 但仍然没有变化。
  • 您在代码中的注释说at a rate of one frame per secondget_frame 会在一秒钟内返回相同的图像。无论如何,没有sleeps 的无限循环会冻结计算机是可以理解的(也许linux 更擅长管理资源)。但我不知道为什么这会在 linux 中而不是在 windows 中显示图像...尝试检查从 get_frame 返回的日期。
  • @zvone 我很困惑。我以每秒一帧的速度流式传输。

标签: python windows python-3.x flask mjpeg


【解决方案1】:

看来您可能需要仔细检查 app.py 中图像文件的路径,即确保它们位于同一目录中,或者如果它们位于 /images 目录中,请仔细检查路径文件或它们从那里开始。

作为测试,(git) 克隆 Miguel 的项目并运行它,看看是否得到相同的结果。

https://blog.miguelgrinberg.com/post/video-streaming-with-flask

【讨论】:

  • 尝试克隆但浏览器仍然显示损坏的图像图标。
猜你喜欢
  • 1970-01-01
  • 2011-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 2014-08-10
相关资源
最近更新 更多