如何在flask后端运行python脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45553629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:07:06  来源:igfitidea点击:

How to run a python script on flask backend?

pythonflask

提问by Jason Stein

I have a small flask app where it takes user input and returns some text. Here the user input is fed to another python script say temp.py and this temp.py will return a value which should be returned to user. For eg:

我有一个小烧瓶应用程序,它接受用户输入并返回一些文本。在这里,用户输入被馈送到另一个 python 脚本中,比如 temp.py,这个 temp.py 将返回一个应该返回给用户的值。例如:

flask.py

烧瓶.py

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def result():
    return render_template("index.html")

@app.route('/getconfig', methods=['GET', 'POST'])
def config():
    value = request.form['config']
    print ("This is the user value :  ", value);
    // This value is written to a file say x.pol and my temp.py reads from x.pol file and writes the output to y.pol. I'm not sure how to trigger the script like "python temp.py" on the server.
    // The reason I'm doing this because I don't want to tweak the third party tool where, the third party tool reads from input files and generates output files. 

    return content_generated_by_temp.py // by reading y.pol.

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

By the way, temp.py is itself a nightmare. I understood what the tool does. For more info about the tool: Google Caprica

顺便说一下,temp.py 本身就是一场噩梦。我了解该工具的作用。有关该工具的更多信息:Google Caprica

回答by Jason Stein

Wrap whatever temp.pyis doing in a function. Place it in the same directory as flask.py. Call import tempin flask.py, then use temp.myfunction()

temp.py正在执行的操作包装在一个函数中。将其放在与flask.py. 通话import tempflask.py,然后使用temp.myfunction()