【发布时间】:2017-06-23 18:25:18
【问题描述】:
我有一个 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 需要传递参数。
抱歉,如果我在解释问题时不清楚,请告诉我是否可以更好地解释任何内容以帮助理解问题。
谢谢
【问题讨论】:
-
为什么不显示main.py的代码?
-
我觉得它只会增加帖子的长度,它相当大,本质上是一个用于垃圾邮件预测的贝叶斯分类器。
-
但是你为什么不能直接导入它并调用它定义的任何函数呢?
-
我确实尝试过导入它,但它需要 2 个文本文件作为参数。我希望用户输入这些文件名或通过我的烧瓶应用程序的前端上传文件,然后后端将主脚本称为 main.py file1.txt file2.txt 到目前为止,我只能通过前端获取文件名,不知道如何调用主脚本,同时将这些名称作为参数传递。
-
这就是为什么您应该显示代码。目前尚不清楚导入需要参数是什么意思。它从哪里得到它们?它是如何使用它们的?
标签: python html flask python-import