harveyslash
harveyslash

Reputation: 6014

Unable to run python From PHP

I would like to run a few python scripts(I am aware of the risks , but I HAVE to get it done)

i tried using :

echo exec('python --version ');

as well as echo shell_exec('python --version ');

Also tried '/usr/bin/python ' instead of just python but I dont get any output at all. I have even added the www-data to the sudoers list, still not working.

What should I do ?

Running debian and python 2.7

Upvotes: 3

Views: 2159

Answers (4)

Arun Kumar
Arun Kumar

Reputation: 21

The reason you can't run python script from PHP is that, the system call requires to be root.Even if you make a sudo call, it requires password.So what you can do is add this line to the end of file : /etc/sudoers

www-data ALL=(ALL) NOPASSWD:ALL

In this way, any sudo call from the PHP will not require a password. Go ahead and execute the python script for an eg. exec("sudo python /home/pi/test.py"); This works for me.Let me know if it works.

Upvotes: 1

vim
vim

Reputation: 1550

To capture the output of python --version use the following:

exec('python --version 2>&1', $output);
var_dump($output);

python --version outputs to stderr, which is a bug. It has been fixed in Python 3.4.0 (see changelog, issue #18338).

Upvotes: 2

lafor
lafor

Reputation: 12776

It seems python --version prints version info to stderr instead of stdout for some reason, so you'll need to redirect former to latter:

exec('python --version 2>&1');

Also, note that exec's return value is just the last line of the executed command's output. If you want to catch full output from command that returns multiple lines, you'll need to provide an array as exec's second argument:

$output = array();
exec($some_command, $output);

Upvotes: 5

Peter Körner
Peter Körner

Reputation: 111

When you type python on your Command-Line, your Shell is searching all folders which are configured in the Environment-Variable $PATH. Your PHP-Interpreter has a different Environment and therefore maybe does not find the python-Binary.

Try to obtain the complete Path to your python-Binary by running which python in your Shell and try to use this in PHP.

Upvotes: 0

Related Questions