![](/img/trans.png)
[英]Python: subprocess and running a bash script with multiple arguments
[英]Import with multiple arguments: running python script in flask
我有一个 python 脚本 main.py,它接受两个参数(2 个文本文件)
我使用的是 MAC OS X Python 2.7
这在终端上很容易运行:
python main.py train.txt sample.txt
我现在使用 Flask 开发了一个小型前端,其中包含非常小的 HTML,如下所示:
#front.py FLASK
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/signup', methods = ['POST'])
def signup():
email = request.form['email']
email1 = request.form['email1']
# command below is just for testing, I wish to implement the same as this would if this would be typed in terminal.
print("main.py " + email + " " + email1)
return redirect('/')
if __name__ == "__main__":
app.run()
和 HTML
<!DOCTYPE html>
<html>
<head>
<title>T</title>
</head>
<body>
<form action="/signup" method="post">
<input type="text" name="email"></input>
<input type="text" name="email1"></input>
<input type="submit" value="Signup"></input>
</form>
</body>
</html>
这个 HTML 代码只是使用一个表单来接收 2 个参数(我发现这比 JS 更容易,因为我没有这方面的经验)。
我刚刚写了
print("main.py " + email + " " + email1)
上面的命令来测试,它现在没有任何用处。
参数的使用:
#main.py
from filter import Filter
import sys
# Get arguments from user
train = sys.argv[1]
messages = sys.argv[2]
# Open files for reading and writing
train_file = open(train, "rb")
messages_file = open(messages, "rb")
predictions_file = open("predictions.txt", "w")
# Create new filter and train it using the train-file
f = Filter()
f.train(train_file)
#filter the messages in messages_file, write results to predictions_file
f.filter(messages_file, predictions_file)
# Close all the files
train_file.close()
messages_file.close()
predictions_file.close()
我现在希望通过这个烧瓶应用程序本身运行我的 main.py 脚本,并想知道这是怎么可能的。
我正在使用 import main 和另一个应用程序装饰器说 /exec 并手动将 URL 从 127.0.0.2000 更改为 127.0.0.2000/exec 但这给出了错误,因为 main 需要传递参数。
抱歉,如果我在解释问题时不清楚,请告诉我是否可以以更好的方式解释任何内容以帮助理解问题。
谢谢
您需要稍微修改此脚本。 你应该把所有处理输入的代码放在一个name == '__main__'
块中,就像你在 Flask 应用程序中所做的那样,其余的代码放在你从该块调用的函数中:
def do_stuff(train, messages):
# Open files for reading and writing
train_file = open(train, "rb")
...
predictions_file.close()
if __name__ == '__main__':
# Get arguments from user
train = sys.argv[1]
messages = sys.argv[2]
do_stuff(train, messages)
现在你的 Flask 应用程序可以调用main.do_stuff(email, email1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.