Can't execute Python script from PHP document

前端 未结 2 840
春和景丽
春和景丽 2020-12-22 02:10

I am running a PHP document on an Apache server on my Raspberry Pi and I want it to run a file when a button is clicked. I put some echo commands under the command to make t

相关标签:
2条回答
  • 2020-12-22 02:42

    This worked for me:

    test.php

    <?php
        echo shell_exec("python test.py");
    ?>
    

    test.py

    f = open("test.txt", "a+")
    f.write("hiya buddy!!\n")
    f.close()
    print "some output"
    

    Here's my relevant ls -l output from /var/www/html:

    jason@Jason-one /var/www/html $ ls -l
    -rw-r--r--  1 jason    jason    44 Sep 20 18:12 test.php
    -rwxr-xr-x  1 jason    jason    82 Sep 20 17:44 test.py
    -rw-rw-rw-  1 jason    jason    38 Sep 20 18:15 test.txt
    

    Since I don't have GPIO pins on my laptop, I decided to write to a file as a test. Notice I didn't have to use sudo because of the way I set the permissions on test.py.

    0 讨论(0)
  • 2020-12-22 02:45

    as you said you are running it like apache->php->shell_exec(SUDO..)

    So the apache user has to be in sudoers file, better you don't give sudo to apache instead give apache (www-data) user right to run your python program

    put first line in your python script: #!/usr/bin/env python so the script knows which program to open it with..

    then

    change group:

    chgrp www-data /path/to/python-script.py
    

    make it executabel

    chmod +x /path/to/python-script.py
    

    try it

    shell_exec("/path/to/python-script.py");
    

    I hope it works ;)

    TIPP: Apache and PHP are for delivering Documents and Strings, if you want some kind of control and an API start with nodejs and https://www.npmjs.com/package/rpi-gpio package. This way you will have one place for your solid automation environment

    0 讨论(0)
提交回复
热议问题