【发布时间】:2019-01-19 09:42:46
【问题描述】:
我正在用 python 构建一个网站,我希望能够通过一个按钮启动和停止“motiondetect.py”。 (合并两个按钮)
现在我有两个单独的“Start motiondetect”和“Stop motiondetect”按钮。我想让 merged* 按钮在您第一次单击时启动运动检测,第二次单击应该停止它。
这是我的代码 sn-ps:
Python 开始:
@app.route("/start", methods=["GET", "POST"])
def start_motion():
global proc
#global FNULL
#global APP_ROOT
print(" > Start")
proc = subprocess.Popen(["python", "motiondetect.py"])#, stdout=FNULL,
stderr=subprocess.STDOUT)
print(" > Process id {}".format(proc.pid))
return "Start Detection"
Html 开始:
$(document).ready(function(){
$("#start_button").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/start",
data: {},
success:function(result){
$("#start_button").html(result);
}});
});
});
Python 停止:
@app.route("/stop", methods=["GET", "POST"])
def stop_motion():
global proc
print(" > Stop")
proc.kill()
#os.system("echo > close")
#print(" > Process killed")
#time.sleep(2)
#os.system("rm close")
return "Stop Detection"
HTML 停止:
$(document).ready(function(){
$("#stop_button").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/stop",
data: {},
success:function(result){
$("#stop_button").html(result);
}});
});
感谢您的宝贵时间,并为我的无知感到抱歉。
【问题讨论】:
-
您可能需要将按钮单击的状态存储在某处,可能在前端,例如当用户第一次单击按钮时,您应该保存一个状态
first,当用户单击时再次,然后您将拥有一个状态second,以便您可以随后终止该进程,该用户已第二次单击该按钮。您也可以更改按钮中的文本,最初可能是start,一旦用户点击start,文本可以动态更改为stop。 -
@user2906838 我猜你是对的。我对网络开发真的很陌生,所以请原谅我,但我将如何将它存储在前端。作为python中的变量?如果不是要求太多,你能给我一个例子吗?无论如何谢谢!
-
好的,那我给你准备一个解决方案。
-
我给你写了一个例子,请查收。