简体   繁体   English

通过网站启动Python脚本(单击按钮)

[英]Initiate a Python Script via a Website (Click of a Button)

I have a small web panel on which I would like to control a python script that continuously collects data from a sensor (while loop). 我有一个小的Web面板,我想在该面板上控制一个python脚本,该脚本不断从传感器收集数据(while循环)。 I would like to be able to start and stop this script by simply clicking a button. 我希望能够通过单击一个按钮来启动和停止该脚本。 I know of a method of enabling the script to stop, but starting it seems to be a bit of a hassle. 我知道一种使脚本停止的方法,但是启动它似乎有点麻烦。

I have tried several solutions that included jQuery.ajax requests, but that sadly did not start the script. 我尝试了包括jQuery.ajax请求在内的几种解决方案,但可悲的是没有启动脚本。 What should be noted is that I only want to start the script, I do not want any output/return values from it, so the script needs to run asynchronously in the background (which is what Ajax is for after all). 应该注意的是,我只想启动该脚本,不需要它的任何输出/返回值,因此该脚本需要在后台异步运行(这毕竟是Ajax的目的)。

Here are a few solutions that could potentially work: 1) Install Flask. 以下是一些可能可行的解决方案:1)安装Flask。 The thing is I actually really want to avoid that and instead find a direct way to do this. 问题是我实际上真的想避免这种情况,而是想找到一种直接的方法来做到这一点。 After all, I just want to make a request to the script so it gets executed. 毕竟,我只想向脚本发出请求,以便脚本得以执行。 2) Execute it by installing PHP on the server and use exec(). 2)通过在服务器上安装PHP并使用exec()来执行它。 But this again goes back to the point that I actually prefer to use Python directly or do it through a jQuery/Ajax call that actually works. 但这又回到了我实际上更喜欢直接使用Python或通过实际起作用的jQuery / Ajax调用来实现这一点。

Any suggestions on how to set this up? 关于如何进行设置的任何建议? If there is really no other way, I suppose that installing PHP and using it to execute the files is the only way. 如果真的没有其他方法,我认为安装PHP并使用它执行文件是唯一的方法。 If that is true, is it actually possible to have both Python scripts run asynchronously through the PHP exec() call? 如果是这样,实际上是否可以通过PHP exec()调用来同时运行两个Python脚本?

just wanted to answer my own question as, after extensive research, I found a solution to my initial problem. 我只是想回答我自己的问题,因为经过大量研究,我找到了解决最初问题的方法。 Here is a description: 描述如下:

The Button: Here we simply have the onclick event for our Javascript function. 按钮:这里我们的Javascript函数只有onclick事件。

<div class="col-md-4"><button id="script_run" type="button" class="btn btn-primary" onclick="runscript()">Test</button></div>

The Javascript Code: On the Javascript side, I have created 2 functions. Javascript代码:在Javascript方面,我创建了2个函数。 One that is there to update the color of the button (so the user will know if the script is currently running or not) and one script which actually makes an HTTP request via Ajax to our Python script. 其中一个用于更新按钮的颜色(这样用户就可以知道该脚本当前是否正在运行)和一个实际通过Ajax向我们的Python脚本发出HTTP请求的脚本。 What you will notice here is that for the button, we are checking whether a local file (RUNNING.txt) exists. 您将在此处注意到的是,对于该按钮,我们正在检查是否存在本地文件(RUNNING.txt)。 This is because RUNNING.txt is a temporary file that is created when our Python script is executed, here we store the ID's of our simultaneously running processes so that we can later terminate them. 这是因为RUNNING.txt是在执行Python脚本时创建的临时文件,此处我们存储了同时运行的进程的ID,以便以后可以终止它们。

function changebutton() {
    $.ajax({
        url: "RUNNING.txt",
        error: function() {
            document.getElementById('script_run').className = "btn btn-danger";
            document.getElementById('script_run').innerHTML = "OFFLINE";
        },
        success: function() {
            document.getElementById('script_run').className = "btn btn-success";
            document.getElementById('script_run').innerHTML = "ONLINE";
        }
    });
}
changebutton();

function runscript() {
    if (document.getElementById('script_run').innerHTML == "ONLINE") {
        $.ajax({
            type: "POST",
            url: 'main.py',
            data: {offline: "True"}
        })
        .done(setTimeout(function(){
            changebutton();
        }, 50000));
    }
    else {
        $.ajax({
            url: 'main.py'
        })
        .done(setTimeout(function(){
            changebutton();
        }, 50000));
    }
};

The Python Code: What we are doing here is that when the script is called, we are creating the file RUNNING.txt. Python代码:我们在这里所做的是,当调用脚本时,我们正在创建文件RUNNING.txt。 Then we actually get to the core part: which is the asynchronous processing of our functions. 然后,我们实际上到达了核心部分:这是我们函数的异步处理。 This is achieved through the multiprocessing library. 这是通过多处理库实现的。 After that we save the process ID's in RUNNING.txt and wait for an event. 之后,我们将进程ID保存在RUNNING.txt中,然后等待事件。 If the script is called again (this leads us to the else statement), we execute the abort() function, which simply uses the os.kill() function to kill our processes. 如果再次调用脚本(这将导致我们转到else语句),我们将执行abort()函数,该函数仅使用os.kill()函数来终止进程。 That's it :) 而已 :)

import multiprocessing
import cgi
import os
import os.path
import signal

import YOURFUNCTION1
import YOURFUNCTION2

def abort():
    f = open('RUNNING.txt', 'r')
    process = f.readline()
    process = filter(None, process.split(","))

    for p in process:
        os.kill(int(p), signal.SIGQUIT)

    f.close()
    os.remove('RUNNING.txt')

def main():
    if not os.path.isfile("RUNNING.txt"):
        f = open('RUNNING.txt', 'w+')

        for func in [YOURFUNCTION1, YOURFUNCTION2]:
            processes.append(multiprocessing.Process(target=func))
            processes[-1].start()

        for p in processes:
            f.write(str(p.pid))
            f.write(",")
        f.close()

        choice = raw_input("Press X to abort all processes: ")
        if choice == "X":
            abort()
    else:
        print "Processes already operational."
        if form.getvalue('offline') == "True":
            abort()

Hope that I could help someone with this :) 希望我可以帮助某人:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM