簡體   English   中英

使用多個參數導入:在燒瓶中運行 python 腳本

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM