0

I have created .py file that is doing job of communicating on UART quite well. Now I want to run that file on button clicking from browser. I have tried exec("python filename.py"); in PHP but that didn't worked. I have also tried system().

  • Can you give more details ? Is this python script like a daemon or it simply exits after doing some tasks? Which web server are you running on PI ? – RikiRiocma May 10 '17 at 19:16
  • Perhaps this is something that you could do using Remi? Certainly if you're just wanting a single-use website with a button that is used to run your script that's one of the easiest ways (it's all done with Python too). – Tom Oct 25 '17 at 2:15
1

Here an example how to did it with cherrypy3 on a raspbian jessie.

  • Install cherrypy3 with sudo apt install python-cherrypy3.
  • Create a file button.py with the following content:

    #!/usr/bin/python
    # coding: utf-8
    
    import cherrypy
    import subprocess
    
    text = """
    <html><body>
    <form method='get' action='do_it'>
    <input type='submit' value='Submit' />
    </form></body>
    {}
    </html>
    """
    
    
    class PiButton(object):
        @cherrypy.expose
        def index(self):
            return text.format("")
    
        @cherrypy.expose
        def do_it(self, *vargs, **kwargs):
            #command = "ls /"
            command = "python my_other_python.script.py"
            result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8').replace('\n', '<br>')
            result2 = "command: {!r}<br>result:<br>{}".format(command, result)
            return text.format(result2)
    
    
        if __name__ == "__main__":
            cherrypy.engine.autoreload.unsubscribe()
            cherrypy.config.update({'server.socket_host': "0.0.0.0", 'server.socket_port': 8181})
            cherrypy.quickstart(PiButton(), '/', {'':{}})
    
  • Run it with python button.py
  • Now open a browser and enter the adress: http://<ip-of-raspberrypi>:8181 replace <ip-of-raspberrypi> with the actual IP of your raspberrypi.
0

I'd suggest making the button redirect the URL to making it have a location.href?CommandVariable=

Then, using PHP

if (isset($_GET['CommandVariable']))
{
    exec( "python filename.py" );
}

This is basically saying: When I push the button, I will place a command variable in the URL. And the PHP will say: Is the Command Variable there? It is? Ok now I can execute this line of code.

-1

You'll want to write an sh script that looks like

python path/to/the/pyton/filename.py

And run that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.