Execute Python program using PHP
Can I simply execute Python program using PHP like this? (in a browser)
exec("python myProgram /Ap开发者_高级运维plications/MAMP/htdocs/somefile.xml");
or like this:
exec("/path/to/python path/to/myProgram /Applications/MAMP/htdocs/somefile.xml");
Is any of this method correct?
If not, what should be the right way to do it?
Thanks
I would prefer using proc_open()
as suggested by mvds as you can't write to STDIN nor read from STDOUT with exec()
/shell_exec()
, as well as providing your own set of environment variable -$_ENV
.
A sample snippet extracted from my code:
$process = proc_open(
"{$command}",
array(
array('pipe', 'r'),
array('pipe', 'w'),
array('pipe', 'w')
),
$pipes,
NULL,
$_ENV
);
if(is_resource($process)){
fwrite($pipes[0], $string);
fclose($pipes[0]);
$rt = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$rtErr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$exitCode = proc_close($process);
}
Read more: http://php.net/manual/en/function.proc-open.php
if you want to capture output as well, use proc_open
(full fd connectivity, i.e. input and output) or popen
(either in- or output)
Yeah, why not?
Note that you are not executing this "in the browser" but rather on the server side, while the page is being pre-processed.
Consider that the page will not return until the exec
has finished, so it really depends on what exactly you are trying to do.
精彩评论