You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从PHP调用Python脚本无输出求助:Linux环境执行异常排查

PHP调用shell命令正常,但无法执行Python脚本的问题

环境配置

  • 操作系统:Ubuntu 22.04
  • PHP版本:8.0
  • Python版本:3.10

测试场景

测试用Python脚本(test.py)

#!/usr/bin/env python
Print("Hello Word")  # that simple

该脚本在终端执行python3 test.py可正常输出“Hello World”

PHP调用脚本(myscript1.php)

执行后无输出,生成的test.txt为空:

$command = escapeshellcmd("/mysite.com/path/python3 test.py ");
$out = shell_exec($command);
file_put_contents( $txt_path.'test.txt', $out);   // test.txt is empty

对比测试:执行Linux命令正常(myscript2.php)

out.txt能正常生成文件列表:

$output = shell_exec('ls -lart');
$t1= "<pre>$output</pre>";
file_put_contents( $txt_path.'out.txt', $t1 ) ;  // out.txt contains the list of files

已做排查操作

  • 给相关路径和脚本赋予全权限:
    sudo chmod a+rwx /mysite.com/path/ 
    chmod +x  test.py   
    
  • 尝试过passthru()、shell_exec()、exec()等所有shell执行函数
  • 确认php.ini的disabled_functions中未禁用上述函数(已移除pcntl_exec())

解决建议

1. 修复Python脚本语法错误

Python是大小写敏感语言,脚本中的Print应改为小写print,否则执行时会直接抛出NameError,导致无标准输出返回给PHP:

#!/usr/bin/env python3
print("Hello World")

2. 修正命令中的路径问题

确保命令中使用Python解释器和脚本的绝对路径:

  • 先通过终端获取python3的绝对路径:which python3,比如得到/usr/bin/python3
  • 修改PHP中的命令:
    $command = escapeshellcmd("/usr/bin/python3 /mysite.com/path/test.py");
    

或者直接利用脚本的可执行权限(需确保shebang正确指向python3):

$command = escapeshellcmd("/mysite.com/path/test.py");

3. 捕获错误输出排查问题

shell_exec()默认只捕获标准输出(stdout),错误输出(stderr)会被丢弃,可将错误输出重定向到标准输出,以便查看脚本执行的报错信息:

$command = escapeshellcmd("/usr/bin/python3 /mysite.com/path/test.py 2>&1");
$out = shell_exec($command);
file_put_contents( $txt_path.'test.txt', $out);

这样test.txt中会包含脚本执行的错误详情,帮助定位问题。

4. 检查PHP运行用户的权限与环境

PHP通常以www-data用户运行,需确保该用户能访问test.py所在路径,以及Python解释器的路径。可通过以下命令验证:

sudo -u www-data python3 /mysite.com/path/test.py

如果该命令执行失败,说明权限或环境问题,需进一步调整。

内容的提问来源于stack exchange,提问作者Brian Tracy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:23:01