I have a simple PHP function that is supposed to execute a Pyton script when its called. I have tried this sort of function multiple times in my php programs, but somehow this time this function is not executing the python script at all. When I access the script from the command prompt and run python testing.py
then it successfully gets executed. One thing that I want to mention that this script has some serious implementations of python's NLTK library, and takes more than 20 seconds to execute and perform its operations (i.e. data process and storing to db). Is this delay in the execution which is causing this problem or is there something else that I am missing this time?
function success(){
$mystring = exec('python testing.py');
$mystring;
if(!$mystring){
echo "python exec failed";
}
else{
echo "<br />";
echo "successfully executed!";
}
To call a Python file from within a PHP file, you need to call it using the shell_exec function.
shell_exec — Execute command via shell and return the complete output as a string.
PHP exec will wait until the execution of the called program is finished, before processing the next line, unless you use & at the end of the string to run the program in background.
you have to use full path for the python
and for your file. you may find the former from the which python
command, that most likely outputs '/usr/bin/python' and you should already know the latter. so your command would look like this:
$mystring = exec('/usr/bin/python /home/user/testing.py');
and you should make sure your python script has all appropriate permissions, because your web-server most probably is running as a different user, so permissions should be "-rwxrwxr-x" or something close.
try to use exact path to the python program.
$mystring = exec('python testing.py');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With