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

Node.js调用Python脚本如何等待脚本执行完成后再执行后续代码

你遇到的输出顺序问题是因为 PythonShell.run 是异步回调API,你传入的回调函数会在Python脚本执行完成后才触发,而回调外的 console.log("amit") 是同步代码,会在调用PythonShell.run后立刻执行,不会等待回调结果。

最简单的实现方式

方案1:最小改动(无额外封装)

直接把所有需要等Python脚本执行完再运行的代码,放到PythonShell.run的回调函数内部即可,修改后代码如下:

PythonShell.run('public/python/dag.py', null, function (err,result) {
    if (err) throw err;
    console.log(result)
    // 所有依赖Python执行结果的后续代码都放在此处
    console.log("amit")
})        

方案2:async/await写法(适合逻辑复杂的场景)

如果后续有大量依赖Python执行结果的逻辑,嵌套回调容易产生可读性问题,可以把调用封装为Promise,用async/await的同步写法实现顺序执行:

// 封装Python调用为Promise
function runPythonScript() {
  return new Promise((resolve, reject) => {
    PythonShell.run('public/python/dag.py', null, function (err, res) {
      if (err) return reject(err)
      resolve(res)
    })
  })
}

// 按顺序执行业务逻辑
async function main() {
  try {
    const pyResult = await runPythonScript()
    console.log(pyResult)
    console.log("amit")
    // 其他后续业务逻辑都可以放在此处按顺序写
  } catch (err) {
    throw err
  }
}

main()

两种方案都可以达到你期望的输出效果,方案1修改最少,最适合你当前的简单使用场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:24:02