繁体   English   中英

从 flask 运行 python 脚本

[英]run python script from flask

I have a python script (script.py) that when I run it in the console it keeps receiving data in JSON format, now I want to visualize the output of the console on a web page or to be able to execute the script.py并捕获 output 以在浏览器中查看,根据我所阅读的内容,我了解到使用 FLASK 我可以做到这一点,一个示例或指南来实现它。

from flask import Flask

app = Flask(__name__)

@app.route("/")
def code():
    out = open(r'output.py', 'r').read()
    return exec(out)

if __name__ == '__main__':
    app.run(host='0.0.0.0')

///////////////////////////////////////

builtins.RuntimeError

RuntimeError:线程 'Thread-9' 中没有当前事件循环。 Traceback(最近一次通话最后一次)

File "..//python3.6/site-packages/flask/app.py", line 2301, in __call__

return self.wsgi_app(environ, start_response)

File "..//python3.6/site-packages/flask/app.py", line 2287, in wsgi_app

response = self.handle_exception(e)

File "..//python3.6/site-packages/flask/app.py", line 1733, in handle_exception

reraise(exc_type, exc_value, tb)

File "..//python3.6/site-packages/flask/_compat.py", line 35, in reraise

raise value

File "..//python3.6/site-packages/flask/app.py", line 2284, in wsgi_app

response = self.full_dispatch_request()

File "..//python3.6/site-packages/flask/app.py", line 1807, in full_dispatch_request

rv = self.handle_user_exception(e)

File "..//python3.6/site-packages/flask/app.py", line 1710, in handle_user_exception

reraise(exc_type, exc_value, tb)

File "..//python3.6/site-packages/flask/_compat.py", line 35, in reraise

raise value

File "..//python3.6/site-packages/flask/app.py", line 1805, in full_dispatch_request

rv = self.dispatch_request()

File "..//python3.6/site-packages/flask/app.py", line 1791, in dispatch_request

return self.view_functions[rule.endpoint](**req.view_args)

File "/usr/share/server/www/test/index1.py", line 9, in dynamic_page

return exec(file)

File "<string>", line 60, in <module>

///////////////////////////////////////// //////////////////////output.py

#!/usr/bin/env python3

进口 json 进口系统

从手机导入 Runn、BReporter、EventHandler

class NoOpEventHandler(EventHandler):

def on_event(self, event):
    self._reporter.on_event(event)

class VerboseNoOpEventHandler(NoOpEventHandler):

FILTER_EVENTS = False

class JsonReporter(BReporter):

def __init__(self):
    self._has_first_line = False

def on_event(self, event):

    json_data = json.dumps(dict(event), sort_keys=True)

    if self._has_first_line:
        sys.stdout.write(',')
    else:
        sys.stdout.write('[')
        self._has_first_line = True

    sys.stdout.write('\n  {}'.format(json_data))

def close(self):
    sys.stdout.write('\n]')

记者 = JsonReporter()

runner = Runn([ 'tcp://test123:test123@127.0.0.1:5038', ], 记者, handler=NoOpEventHandler) runner.run()

就用这个; 您必须设置debug = True 您不必提供主机进行测试。

if __name__ == "__main__":
    app.run(debug=True)

你应该在终端上看到一个 output ;

* Serving Flask app "my_flask_app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: xxx-xxx-xxx
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

打开 web 浏览器并复制粘贴: http://127.0.0.1:5000/

我将您的代码保存在tmp.py中,然后将其作为python tmp.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def code():
    out = open(r'output.py', 'r').read()
    return exec(out)

if __name__ == '__main__':
    app.run(debug = True)

运行如下:

   (flaskvenv) C:...>python tmp.py

这是 output:

* Serving Flask app "tmp" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: XXX-XXX-XXX
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

这意味着代码运行。 你可能有另一个问题!

我认为问题出在 exec(out) 上。 实际上,exec 是一个程序的动态执行,可以是字符串,也可以是 object 代码,它不返回任何内容,它只是执行一个程序并返回 None。

如果您在不尝试返回 exec(out) 的情况下运行代码,则不会出错。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM