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

使用pm2+虚拟环境通过ecosystem.config.js部署Python脚本报错排查

PM2 结合虚拟环境部署 Python 脚本报错解决

问题详情

用 PM2 的 ecosystem.config.js 配置虚拟环境部署 Python 脚本时,配置代码如下:

module.exports = {
    apps : [{
        name   : "my_app",
        cwd : "/absolute/path-to/my-app/",
        script : "main.py",
        cron_restart : "0 * * * *",
        interpreter: "/absolute/path-to/venv/bin/python",
        log_date_format: "DD-MM HH:mm:ss.SSS"
  }]
}

启动后抛出语法错误:

0|my_app | 10-04 16:03:15.501: SyntaxError: unterminated string literal (detected at line 29)
0|my_app | 10-04 16:03:15.527:   File "/usr/local/lib/node_modules/pm2/lib/ProcessContainerForkBun.js", line 29
0|my_app | 10-04 16:03:15.527:     // Change some values to make node think that the user's application
0|my_app | 10-04 16:03:15.528:                       ^
0|my_app | 10-04 16:03:15.528: SyntaxError: unterminated string literal (detected at line 29)
0|my_app | 10-04 16:03:15.557:   File "/usr/local/lib/node_modules/pm2/lib/ProcessContainerForkBun.js", line 29
0|my_app | 10-04 16:03:15.557:     // Change some values to make node think that the user's application

但以下场景能正常运行:

  • 命令行直接执行:pm2 start main.py --interpreter=../venv/bin/python
  • 移除 cwd,给 script 配置绝对路径(但会导致 Python 脚本读取文件异常)
  • 移除 interpreter,用全局默认 Python 解释器

版本信息:Node v18.19.1、PM2 v6.0.5、Python 3.12.3

解决办法

报错根源是 PM2 v6.x 引入了 Bun 进程容器逻辑,错误地用 Node/Bun 解析了 Python 脚本。可以用以下三种方案解决:

方案1:添加 interpreter_args 配置

强制 PM2 以正确的方式启动 Python 脚本,在配置中加入 interpreter_args: "-u":

module.exports = {
    apps : [{
        name   : "my_app",
        cwd : "/absolute/path-to/my-app/",
        script : "main.py",
        cron_restart : "0 * * * *",
        interpreter: "/absolute/path-to/venv/bin/python",
        interpreter_args: "-u",
        log_date_format: "DD-MM HH:mm:ss.SSS"
  }]
}

方案2:显式设置 exec_mode 为 fork

绕过 PM2 的 Bun 容器逻辑,指定进程模式为 fork:

module.exports = {
    apps : [{
        name   : "my_app",
        cwd : "/absolute/path-to/my-app/",
        script : "main.py",
        cron_restart : "0 * * * *",
        interpreter: "/absolute/path-to/venv/bin/python",
        exec_mode: "fork",
        log_date_format: "DD-MM HH:mm:ss.SSS"
  }]
}

方案3:降级 PM2 到 v5.x 版本

如果上述方案无效,可降级到没有 Bun 逻辑的 PM2 v5 版本:

npm install -g pm2@5.3.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 10:13:13