EthanLWillis
EthanLWillis

Reputation: 950

php exec() and shell_exec()

I currently have a php page that my webserver serves. In order to display all the information I need to display on the page I need output from an external python script. So I have been using the exec() command of php to execute the python script and capture the output in an array of strings as follows:

$somequery = $_GET['query'];
$result = exec("python /var/www/html/query/myscript.py ".somequery."");

//some for loop to loop through entries in result and echo them.

However there are never any entries to be printed, yet when I run the command directly on the console of the server it will output correctly. I've tried echoing out the command on the webpage that I am executing and it's the correct command. The only thing I think it can be is that exec() doesn't stop the rest of the php program from executing before it finishes, leading to the loop i have printing out entries finding that $result is empty.

How can I ensure that exec() finishes executing before the rest of my php script? Are there maybe settings in php.ini that I would need to change? I'm not entirely sure.

EDIT: I've tried running and storing the output of shell_exec("echo hello"); and printing that output, it now prints. However, when running my command that takes a few seconds longer, the program never finishes executing it before going to the next line.

EDIT 2: I found my solution in the following post https://stackoverflow.com/a/6769624 My issue was with with the numpy python package I was using and I simply needed to comment out the line in /usr/lib64/python2.7/ctypes/init.py like the poster did and my script output correctly.

Upvotes: 0

Views: 793

Answers (1)

ashiina
ashiina

Reputation: 1006

The correct way to get your shell output is like this:

exec("python /var/www/html/query/myscript.py ".somequery."", $result);

var_dump($result); //output should be in here

Give it a try.

Upvotes: 2

Related Questions