Calling Python from within PHP using shell_exec

2020-03-27 12:44发布

问题:

My default Web-Application is based on PHP. However, for easiness, I have built a python script that does some analysis. Now I need the php to call the python code and retrieve the output that the python code delivers. Both files are in the same server, not on the same folder however. My current approach, which does not work, looks as following:

$cmd = "/usr/bin/python /var/www/include/sCrape.py -u '$my_url' ";
$response = shell_exec($cmd);
$response = json_decode($response, true);

Now when I try to print out $response, I get the NULL object (it should return an array-string that I should decode through json_decode). Am I doing something wrong with the function? The php is located within /var/www/html/. The following code works when both files are in the same directory:

$cmd = "python sCrape.py -u '$my_url'";
$response = shell_exec($cmd);
$response = json_decode($response, true);

Further information: my_url is input as a sanitized $_POST variable from php, but I have now tried to completely disable sanitizing to test if it would work, but it still didn't (still, the url's path until it reaches the function is longer, as it must be passed on through form-post, whereas in my same-folder-test-case I have simply just declared $my_url). the -u postfix means that the script inputs a url.

Thank you very much in advance!

回答1:

Did you try running /usr/bin/python /var/www/include/sCrape.py -u '$my_url' in a shell? The mistake is probably there.

Try:

$cmd = "/usr/bin/python /var/www/include/sCrape.py -u '$my_url' 2>&1";
$response = shell_exec($cmd);
echo $response;

This should output an error message.

Why?

shell_exec only returns output from the standard output (stdout), if an error occurs it's written "to the" standard error (stderr). 2>&1 redirects stderr to stdout. See In the shell, what does “ 2>&1 ” mean?.

Run python code

You may want to add #!/usr/bin/env python on the first line of your python script and make it executable chmod +x /var/www/include/sCrape.py. Afterwards you should be able to run your script without explicitly calling python. /var/www/include/sCrape.py -u '$my_url'