error on using exec() to call python script

馋奶兔 提交于 2020-01-11 10:13:32

问题


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:


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);



回答2:


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);

?>



回答3:


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.



来源:https://stackoverflow.com/questions/7765473/error-on-using-exec-to-call-python-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!