我正在研究启动python程序,流输出并停止它的UI。它运行一个python子进程并将参数传递给它。我使用烧瓶,HTML来做到这一点。
python程序的输出显示在我的控制台上。但是,我想将其流式传输到网页文本框。我使用"{{ rows }}"
从stream方法和Response中获取值,但是它不起作用。任何人都可以指出如何将其发布到网页上。
Landingpage.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Landing Page</title>
</head>
<body>
<form method="POST" name="models_selectors" id="models_selectors" action="/">
</form>
<h3>Models</h3><select id="down_models" name="down_models">
<option value="RCNN" value="RCNN">RCNN</option>
<option value="Logistic" value="Logistic">Logistic</option>
<option value="FCNN" value="FCNN">FCNN</option>
<option value="SCNN" value="SCNN">SCNN</option>
</select>
<p></p>
<p></p>
<button style="height:100px; font-size:12pt; width:100px" id="button_run" name="button_run" value="run" onclick="run_program(this.id)"> Run </button>
<button style="height:100px; font-size:12pt; width:100px" id="button_stop" name="button_stop" value="stop" onclick="run_program(this.id)"> Stop </button>
<p></p>
<p></p>
<p></p>
<!--<h2>Output: {{ rows }}</h2>-->
<input type="text" id="output_box" name="output_box" value="kjhkjhkj" style="height:500px; widht:2500px; font-size=10pt;">
<textarea id="text_test" name="text_test"> "text box" </textarea>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function run_program(clicked_id)
{
event.preventDefault();
$.ajax({
url: "/",
type: "post",
data: "model=" + $(" #down_models option:selected").text() + "&op=" + clicked_id,
success: alert(clicked_id)
})
};
var source = new EventSource("/");
source.onmessage = function(event) {
document.getElementById("output_box").innerHTML += event.data + "<br/>"
}
</script>
{% for item in rows %}
<h1>{{ item }}</h1>
{% endfor %}
</form>
</body>
</html>
烧瓶程序:
from flask import Flask, Response, Request, render_template, request, stream_with_context
app = Flask("first test")
is_running = False
@app.route("/", methods=["GET"])
def test():
global is_running
is_running = False
return render_template("Landingpage.html", value="hi")
from ui.sample_python_package.models import RCNN, SCNN, LOGI, FCNN, Models_test
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
rv.disable_buffering()
t.generate(context)
# rv.enable_buffering()
return rv
process = None
import subprocess, os
from werkzeug.exceptions import HTTPException
def inner(model, op):
global is_running, process
print("Program: ", is_running, op, model)
if op == "button_run":
if not is_running:
print("Starting to Run....")
proc = subprocess.Popen(
['Python',
"models.py",
model
],
preexec_fn=os.setsid,
stdout=subprocess.PIPE
)
is_running = True
print("Running process")
process = proc
for line in iter(proc.stdout.readline, ''):
if proc.poll() is not None:
is_running = False
break
print(str(line))
# time.sleep(1)
yield {"value": line}
else:
print("I am running sr ", is_running)
elif op == "button_stop":
if is_running:
print("Stopping...")
is_running = False
process.kill()
# os.killpg(process.pid, signal.SIGKILL)
else:
print("Already stopped")
@app.route("/", methods=["POST"])
def process_inputs():
try:
return render_template('Landingpage.html', rows=inner(model=request.form["model"], op=request.form["op"]))
except HTTPException as excep:
print("Exception ", excep)
# raise Exception(excep)
return render_template("Landingpage.html")
if __name__ == "__main__":
app.run(debug=True)
from gevent.select import select
Models.py
class Models_test:
def __init__(self, model_name):
print("Received model name: ", model_name)
self.model_name = model_name
self.counter = 0
self.run()
def get_counter(self):
return self.counter
def run(self):
while(self.counter < 100):
print("Counter: ", self.counter)
self.counter += 1
import time
time.sleep(0.5)
def stop(self):
import sys
sys.exit(-1)
import sys
if __name__ == "__main__":
models = Models_test(sys.argv[1])
sys.exit(-1)
预先感谢, 桑索什