从模块访问变量

时间:2019-03-22 11:07:28

标签: python flask

我必须做一个DIY机器人。为了找出机器人的方向,我正在使用智能手机和PhonePi应用。该应用程序基于Flask服务器。下面给出了用于定向的代码,我将其命名为orientation.py

from flask import Flask 
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)

@sockets.route('/orientation')
def echo_socket(ws):
    while True:
        message = ws.receive()
        raw2 = message.split(',')
        global orient1
        orient1 = float(raw2[0])
        orient2 = float(raw2[1])
        orient3 = float(raw2[2])
        print('x = ', orient1, "is", type(orient1))
        # print('y = ', orient2, "is", type(orient2))
        # print('z = ', orient3, "is", type(orient3))
        ws.send(message)


@app.route('/') 
def hello():
    return 'Hello World!'

if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

我必须从另一个名为robot controller.py的脚本访问变量 orient1 。我试图通过几种方式访问​​变量:

from orientation import *
import orientation
from orientation import orient1

如何从同一文件夹中的其他脚本访问orient1?

1 个答案:

答案 0 :(得分:0)

变量orient1在函数内部,因此您不能从该函数外部的任何位置访问它。

您可以做的是在函数外部设置一个通用变量,以便可以通过getter函数获取它,例如:

from flask import Flask 
from flask_sockets import Sockets

app = Flask(__name__)
sockets = Sockets(app)
orient1 = 0.0

def get_orient1():
    return orient1

@sockets.route('/orientation')
def echo_socket(ws):
    while True:
        message = ws.receive()
        raw2 = message.split(',')
        global orient1
        orient1 = float(raw2[0])
        orient2 = float(raw2[1])
        orient3 = float(raw2[2])
        print('x = ', orient1, "is", type(orient1))
        # print('y = ', orient2, "is", type(orient2))
        # print('z = ', orient3, "is", type(orient3))
        ws.send(message)


@app.route('/') 
def hello():
    return 'Hello World!'

if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

现在,您可以通过以下方式访问它:

from orientation import get_orient1
orient1 = get_orient1()