我有一堆 Python CLI 脚本(适用于 Windows),我想通过 Web 界面提供服务。
为此,我想使用 Flask 创建一个小型“框架”,我将在其上“插入”一个脚本并在特定路线上提供它。
然后,该框架会将 Web 界面的输入“链接”到脚本的输入,并将脚本的输出“链接”到 Web 界面的输出(实时更新)。
(会是终端模拟器吗?)
这是其中一个脚本的示例......我们称之为myapp_outputs.py:
from time import sleep
print("Hello. Let's begin to do lengthy tasks now:\n")
print("Task 1...", end="", flush=True)
sleep(2) # simulating a synchronous blocking task
print("done.\n")
print("Task 2...", end="", flush=True)
sleep(2) # simulating a synchronous blocking task
print("done.\n")
print("Task 3...", end="", flush=True)
sleep(2) # simulating a synchronous blocking task
print("done.\n")
这是另一个脚本的示例......我们称之为myapp_input.py:
print("Starting...")
user = input("What is your name? ")
print(f"Hello {user}!")
现在我想使用 Flask 在网络上为它们提供服务。所以myapp_outputs.py将在myserver.com/myapp_outputs上,而myapp_input.py将在myserver.com/myapp_input上。
因此,为了捕获输出,我使用了subprocess。对于输入,我不知道该怎么做。
我试过的:
from flask import Flask
import subprocess
app = Flask(__name__)
@app.route('/')
def hello():
return 'ok'
@app.route('/myapp_outputs')
def myapp_outputs():
result = subprocess.run(['python', "myapp_outputs.py"], capture_output=True, text=True)
return result.stdout
# PROBLEM: the output is not shown in real time!
# In case there are errors, how do I show them to the user?
# print("stderr:", result.stderr) ???
@app.route('/myapp_input')
def myapp_input():
# Here I just render some web components (an input box and a button)
# to capture the input from the user.
return render_template('myapp_input.html')
@app.route('/myapp_input', methods=['POST'])
def myapp_input_post():
user_input = request.form['text']
# Here I have to forward this input to the script... but how?
result = subprocess.run(['python', "myapp_input.py"], capture_output=True, text=True) # ???
return result.stdout
问题:
myapp_outputs的输出不会实时更新。它只显示所有任务完成后的整个输出。
如果出现错误,如何输出“stderr”?
当应用程序要求时,我不知道如何传递myapp_input的用户输入。
我很感激任何帮助。谢谢你。