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

Laravel执行Python Selenium/Appium脚本报错,求解决方案

问题解决方案

1. 先定位具体错误原因

Laravel的500错误详情会记录在storage/logs/laravel.log文件中,先打开该日志找到对应报错信息,这是排查问题的核心依据。

2. 修复命令路径问题

你的app.py位于Laravel项目的上级目录,执行命令时必须指定正确路径:

  • 相对路径写法:pytest -s ../app.py
  • 更可靠的绝对路径写法:比如mobile-automation目录的绝对路径是/home/yourname/mobile-automation,则命令为pytest -s /home/yourname/mobile-automation/app.py

3. 解决权限问题

web服务器运行用户(如Ubuntu的www-data、CentOS的apache/nginx)需要具备以下权限:

  • 读取app.py文件的权限:执行chmod o+r /path/to/app.py
  • 进入mobile-automation目录的权限:执行chmod o+x /path/to/mobile-automation
  • 若脚本需要生成测试报告等写入操作,需给对应目录添加写入权限:chmod o+w /path/to/report-directory
  • 可临时切换到web用户验证命令是否能正常执行:su www-data -c "pytest -s /path/to/app.py",若执行失败则说明是权限或环境问题

4. 处理环境变量差异问题

web服务器用户的环境变量通常和本地用户不一致,可能找不到pytest或python的执行路径:

  • 先在本地命令行执行which pytest和which python,获取绝对路径(如/usr/local/bin/pytest、/usr/bin/python3)
  • 在控制器的exec命令中使用绝对路径调用:/usr/local/bin/pytest -s /path/to/app.py

5. 优化exec代码以捕获错误细节

修改控制器中的runScript方法,捕获命令输出和返回码,方便调试:

public function runScript()
{
    // 替换为实际的绝对路径命令
    $command = '/usr/local/bin/pytest -s /home/yourname/mobile-automation/app.py';
    $output = [];
    $returnVar = 0;
    
    exec($command, $output, $returnVar);
    
    if ($returnVar !== 0) {
        return response()->json([
            'error' => true,
            'message' => '脚本执行失败',
            'detail' => $output
        ], 400);
    }
    
    return response()->json([
        'success' => true,
        'output' => $output
    ]);
}

6. 额外注意事项

  • 若使用Appium,需确保web用户能访问Appium服务(如本地4723端口),且Appium已启动
  • 若脚本依赖浏览器驱动(如ChromeDriver),需在脚本中指定驱动绝对路径,或确保驱动路径在web用户的环境变量中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:35:02