Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute python in a php script using shell_exec()

Tags:

python

php

I'm experiencing a weird problem in trying to execute python in 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 command. Same for$output = shell_exec("tar --version"); and other applications, such as gzip.

However, if I switch for 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 variants of this kind, I get no results. The command is not being executed, the python bitecode not made and the echo remains silent.

I have also tried with the exec() command with no more success.

like image 389
Cyrille Avatar asked Sep 10 '13 14:09

Cyrille


2 Answers

I think this may help...

looks like the output for the python call needs to be routed properly. I was able to make this work within my index.php file for returning the python version...

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

Here is where I found the answer.

like image 170
JDCartee Avatar answered Sep 28 '22 18:09

JDCartee


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

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

you will need to use absolute path for my_script.py and give all permissions (I am not sure which ones are sufficient) for the python file.

like image 20
Chaithanya Avatar answered Sep 28 '22 19:09

Chaithanya