Run python in PHP script using shell_exec ()

I had a strange problem while trying to execute python on a php server (LAMP). (safe_mode off)

if I type:

$output = shell_exec("ls -lah"); echo "<pre>$Output</pre>"; 

I got the result of the ls . The same goes for $output = shell_exec("tar --version"); and other applications like gzip.

However, if I switch to any of these lines:

 $output = shell_exec("python --version"); $output = shell_exec("python2.7 --version"); $output = shell_exec("/usr/bin/python --version"); $output = shell_exec("python my_script.py"); 

And other options of this kind, I do not get any results. The command fails, python bit code has not been created, and echo remains valid.

I also tried the exec() command without any success.

+4
source share
6 answers

I think this may help ...

it looks like the output for calling python should be configured correctly. I was able to do this work in my index.php file to return the python version ...

 shell_exec("python -V 2>&1"); 

Here I found the answer.

+4
source

I think that the kernel cannot find the path for python, where it is installed .. if you can do echo $ PATH..it will show all the paths where you need to look for the command, if given add your python part and then it can work, or you can specify the absolute path (except / usr / bin /), see if it works. I need to check it too.

0
source

What is he doing

 which python 

tell me both from the command line and from shell_exec ()? It should tell you which (if any) Python interpreter it finds (from $PATH ). Remember that it’s possible that the $PATH used from the Linux command line might not match the $PATH used by shell_exec ()! After you find the Python interpreter you want to use, you may have to hardcode it to shell_exec ().

0
source

If you are trying to run a python script using the following code

 $output = shell_exec("python my_script.py"); 

you will need to use the absolute path for my_script.py and provide all permissions (I'm not sure which ones are enough) for the python file.

0
source

Most likely, the web server does not have the appropriate rights to execute shell commands. To fix this, run the command "sudo visudo" and add the following line to the sudoers file:

www-data ALL = NOPASSWD: ALL

Also, make sure that the / var / www directory belongs to the user and the www-data group (use sudo chown -R www-data: www-data / var / www to set the correct owner). Details here http://www.raspberry-pi-geek.com/Archive/2014/07/PHP-on-Raspberry-Pi

Also see Unable to execute python script with php

0
source

I think you need to go the full way for your python.

for example, use this instead:

 $output = shell_exec("/usr/bin/python full_path/my_script.py") 

instead:

 $output = shell_exec("python my_script.py"); 
0
source

Source: https://habr.com/ru/post/1501485/


All Articles