Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Script Failing to Execute from PHP exec()

Tags:

python

php

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!";
   }
like image 293
khan Avatar asked Mar 24 '13 03:03

khan


People also ask

Can PHP execute Python?

To call a Python file from within a PHP file, you need to call it using the shell_exec function.

What is shell_ exec?

shell_exec — Execute command via shell and return the complete output as a string.

Does PHP exec wait until finished?

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.


2 Answers

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.

like image 99
lenik Avatar answered Sep 17 '22 22:09

lenik


try to use exact path to the python program.

$mystring = exec('python testing.py');
like image 44
Ryan Knopp Avatar answered Sep 20 '22 22:09

Ryan Knopp