我想从 php 函数执行 python 脚本,test.py
。
#!/usr/bin/env python
import random
def test() :
print("test success")
if __name__ == '__main__':
test()
我可以使用 php 命令行成功执行它:
php -r '$message = exec("python3 ~/../scripts/test.py"); print_r($message);'
我已将以下内容添加到我的 php 代码中:
$message = exec("python3 ~/../scripts/test.py", $output, $return_val);
当我执行它时,没有任何输出(开发工具中没有错误)。当我打印变量时,$output
和 $message
为空,$return_val
为 2 ( misuse of shell builtins according to Bash documentation )。
我知道在将以下内容添加到同一函数后允许 exec()
:
if (exec('echo TEST') == 'TEST')
{
echo 'exec works!';
}
什么可能导致此错误?如何使用 php 执行 python 脚本?
最佳答案
您的网络服务器不共享您的主目录,因此 ~
将指向错误的位置。请指定文件的完整路径。
python3
将退出并显示 2
,并在 stderr 上显示一条有用的消息。 Web 服务器错误日志将确认这一点,将 2>&1
添加到您的命令中以将 stderr 捕获为变量中的 stdout 也将确认这一点。
关于php - 从php函数执行python脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49395280/