I'm testing with PHP and Python, I`m trying print a text.
test.py:
import sys
print "x => " + sys.argv[1] + " y => " + sys.argv[2]
When I do:
sudo python test.py 5 9
The output is:
x => 5 y => 9
But when I do this in PHP:
<?php
exec("sudo python /home/pi/python/test.py 6 3");
?>
It shows nothing in the console. Not an error.
I have also tried system() or shell_exec but its not working.
How can this working?
I think the problem is that whatever user your PHP/WebServer is running on, does not have access to sudo, nor /home/pi. All in all, I wouldn't use sudo like this and rather set proper permissions for the user that PHP/WebServer is running on to execute said python script.
To solve it:
Put test.py
in webroot ( /var/www
usually) and remove sudo
from your php script:
<?php
exec("python /var/www/test.py 6 3");
?>
You might also need to provide full path to python binary, like this:
<?php
exec("/usr/bin/python /var/www/test.py 6 3");
?>
To find out where python binary really is stored, you can use command which
like this:
which python
/usr/bin/python
Try
<?php
exec("sudo python /home/pi/python/test.py 6 3 2>&1");
?>
The exec()
function returns the last line of the executed command (see documentation ). In order to see it on the console, you need to output it:
echo exec("sudo python /home/pi/python/test.py 6 3");
If you want to see the full output of your executed command, have a look at passthru()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.