python和全局变量

时间:2014-07-13 16:20:18

标签: python raspberry-pi web.py

如何正确设置全局变量?

# default objects is being set as None (null), after importing the piCamera library
camera = None

之后,我将使用GET定义声明Webcam类:

class Webcam:
    def GET(self):
        web.header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')
        stream=io.BytesIO()
        start=time.time()

        for foo in camera.capture_continuous(stream,'jpeg'):
            web.header('Content-type','--jpgboundary')
            web.header('Content-type','image/jpeg')
            web.header('Content-length',len(stream.getvalue()))
            yield (stream.getvalue())
            stream.seek(0)
            stream.truncate()
            time.sleep(.5)


if __name__ == "__main__":
    camera = picamera.PiCamera()
    global camera
    camera.resolution = (640, 480)
    app = web.application(urls, globals())
    app.internalerror = web.debugerror
    app.run()

我应该在定义Webcam类之前放置if __name__ == "__main__":吗?

这是我对电话的追溯:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/wsgiserver/__init__.py", line 1245, in communicate
    req.respond()
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/wsgiserver/__init__.py", line 775, in respond
    self.server.gateway(self).respond()
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/wsgiserver/__init__.py", line 2018, in respond
    response = self.req.server.wsgi_app(self.env, self.start_response)
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/httpserver.py", line 306, in __call__
    return self.app(environ, xstart_response)
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/httpserver.py", line 274, in __call__
    return self.app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 281, in wsgi
    result = peep(result)
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 261, in peep
    firstchunk = iterator.next()
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 605, in wrap
    yield next()
  File "/usr/local/lib/python2.7/dist-packages/web.py-0.37-py2.7.egg/web/application.py", line 597, in next
    return result.next()
  File "/home/pi/piApp/index.py", line 77, in GET
    for foo in camera.capture_continuous(stream,'jpeg'):
AttributeError: 'NoneType' object has no attribute 'capture_continuous'

2 个答案:

答案 0 :(得分:0)

看起来您将其作为库文件运行,因此__main__部分不会执行。将该代码放在全球范围内。

我猜想这就是你想要的东西:

def main():
    global camera
    camera = picamera.PiCamera()
    camera.resolution = (640, 480)
    app = web.application(urls, globals())
    app.internalerror = web.debugerror
    app.run()

main()

答案 1 :(得分:0)

确保您拥有v4L驱动程序,请尝试以下操作:

sudo modprobe bcm2835-v4l2
相关问题