I am trying to call a simple python script
#!/usr/local/python25/bin/python
print "hello world"
from the following php script
<?php
echo exec("/usr/local/python25/bin/python myfile.py"开发者_开发问答);
?>
But nothing was happened. Please tell me what is wrong here? (I also checked other thread but I could not solve my problem)
Question Solved: I forgot to give the permission to access /usr/local/python25/bin/python. After I did this, the problem solved. Thank you so much for your help!
1.The exec
function just return the last line from the result of the command.
2. The print statement in python (except python 3) automatically adds a newline at the end.
This is the reason you feel nothing was happened.
You can catch the whole output by this way.
exec("/usr/local/python25/bin/python myfile.py 2>&1", $output);
print_r($output);
Kind of an obvious point here, but can you run the python script from a terminal? Does it actually run?
Make sure the script is executable by whatever user PHP is running as - chmod 777 myfile.py
, and just to be safe chmod 777 /usr/local/python25/bin/python
. Also, make sure the python script is in the same directory as the PHP script, which is what your method of calling it requires.
Try changing your PHP script to this, and tell me what you see: (EDITED)
<?php
// Path to the python script - either FULL path or relative to PHP script
$pythonScript = 'myfile.py';
// Path to python executable - either FULL path or relative to PHP script
$pythonExec = '/usr/local/python25/bin/python';
// Check the file exists and PHP has permission to execute it
clearstatcache();
if (!file_exists($pythonExec)) {
exit("The python executable '$pythonExec' does not exist!");
}
if (!is_executable($pythonExec)) {
exit(("The python executable '$pythonExec' is not executable!"));
}
if (!file_exists($pythonScript)) {
exit("The python script file '$pythonScript' does not exist!");
}
// Execute it, and redirect STDERR to STDOUT so we can see error messages as well
exec("$pythonExec \"$pythonScript\" 2>&1", $output);
// Show the output of the script
print_r($output);
?>
If you want to capture the subprocess' stdout, you should use passthru
Also you don't need the first line of that python script if you're calling the python interpreter directly.
精彩评论