donglang6656 2018-03-20 22:39
浏览 75
已采纳

从php函数执行python脚本?

I want to execute a python script,test.py, from a php function.

#!/usr/bin/env python
import random

def test() :
   print("test success")

if __name__ == '__main__':
    test()

I can successfully execute it using php command line:

php -r '$message = exec("python3 ~/../scripts/test.py"); print_r($message);' 

I've added the following to my php code:

$message = exec("python3 ~/../scripts/test.py", $output, $return_val); 

When I execute it, nothing is output (no errors in devtools). When I print the variables, $output and $message are empty and $return_val is 2 (misuse of shell builtins according to Bash documentation).

I know exec() is allowed after adding the following into the same function:

if (exec('echo TEST') == 'TEST')
    {
      echo 'exec works!';
    }

What could be causing this error? How can I execute the python script with php?

  • 写回答

1条回答 默认 最新

  • duanmeng3573 2018-03-20 22:42
    关注

    Your web server does not share your home directory, so ~ will point to the wrong place. Specify the full path of the file instead.

    python3 will exit with 2 when it can't find the file, along with a helpful message on stderr. The web server error logs will confirm this, as will adding 2>&1 to your command to capture stderr as stdout in your variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab提取运动物体的坐标
  • ¥15 人大金仓下载,有人知道怎么解决吗
  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥15 python安卓开发
  • ¥15 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码
  • ¥15 stm32标准库的PID角度环
  • ¥15 ADS已经下载好了,但是DAS下载不了,一直显示这两种情况,有什么办法吗,非常急!
  • ¥100 Excel 点击发送自动跳转outlook邮件