2

For example, I have a file python

work1.py

from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)

And i have a file php to run file python via shell_exec function

 <?php
$result=shell_exec("sudo python work1.py");
echo $result;
?>

But when i run, nothing display. So what's problem? Please help me. Thanks.

Lộc Hà
  • 21
  • 4
  • 1
    Have you tried putting `sudo python work1.py` between quotation marks? Because your PHP script should fail with a `Parse error: syntax error, unexpected (T_STRING)`, you can also enable [error reporting](https://stackoverflow.com/q/845021/5914775) to see if there are any other errors. – Tom Udding Jun 08 '17 at 07:48

4 Answers4

2
$result=shell_exec(sudo python work1.py);

I think a syntax error occurs here, you may try:

$result=shell_exec('sudo python work1.py');
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
David Zhang
  • 468
  • 7
  • 10
0

Try it like this:

<?php
$result= shell_exec(sudo /usr/bin/python3 work1.py);
echo $result;
?>
0

Why would the script return some value? Your python statement will continue to be in execution. Add break statement in the script

from time import sleep
while True:
    print "Send 1"
    sleep(2)
    print "Send 2"
    sleep(2)
    break

PHP CODE

<?php
    $result=shell_exec('sudo python work1.py');
    echo $result;
    ?>
user3411846
  • 178
  • 1
  • 3
  • 13
0

I think that the 'sudo' command is probably attempting to prompt you for a password, but there is no way for you to enter one when calling via PHP. Try removing the 'sudo', and perhaps then it will work.

If you need to be root to do some task in your Python script, then consider using setuid flag, http://linuxg.net/how-to-set-the-setuid-and-setgid-bit-for-files-in-linux-and-unix/

jdpipe
  • 232
  • 1
  • 11