使用多个参数导入:在flask中运行python脚本

时间:2017-02-06 17:48:43

标签: python html flask python-import

我有一个python脚本main.py,它接受两个参数(2个文本文件)

我使用的是MAC OS X. Python 2.7

这可以在终端上轻松运行:

python main.py train.txt sample.txt

我现在使用带有非常小的HTML的Flask开发了一个小型前端,如下所示:

  #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和另一个app decorator说/ exec并手动将URL更改为127.0.0.2000到127.0.0.2000/exec但这是错误,因为main需要传递参数。

很抱歉,如果我在解释问题时不清楚,请告诉我是否可以更好地解释任何问题,以帮助您解决问题。

谢谢

1 个答案:

答案 0 :(得分:3)

您需要稍微修改此脚本。您应该像在Flask应用程序中那样将处理输入的所有代码放在name == '__main__'块中,其余部分放在您从该块调用的函数中:

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)