2

Possible Duplicate:
Call Python From PHP And Get Return Code

probably a very stupid question I have a python module lets say hi.py which have the following

print "hi"

now I want to execute this file from php

<?php

#code here
?>

So how do I call that python file from php. Thanks

Community
  • 1
  • 1
frazman
  • 32,081
  • 75
  • 184
  • 269

2 Answers2

5

Use the exec function to invoke Python.

Example:

$output = array();
exec("python hi.py", $output);
var_dump( $output);

There are other commands for executing commands on the machine PHP is running on, see the docs.

nickb
  • 59,313
  • 13
  • 108
  • 143
  • when id do the above.. There is no output in the browser.. How do I get that "hi" output on the browser – frazman Nov 28 '11 at 23:42
  • use `exec("command", $output_array);` it's in a [docs](http://php.net/manual/en/function.exec.php) – Jan Vorcak Nov 28 '11 at 23:45
  • 1
    @Fraz - I've updated my answer to show you how to capture the output. As Jan Vorcak pointed out, it is in the PHP manual. – nickb Nov 28 '11 at 23:47
1

you can call php exec function and call

python -c "print 'hi'"

or if you have larger module you can use

-m mod : run library module as a script (terminates option list)

so in the end I'd use

exec("python -m hi");
  1. and don't forget to configure PYTHON_PATH on your server if needed
  2. be careful doing this kind of stuff
Jan Vorcak
  • 19,261
  • 14
  • 54
  • 90