首页 > 解决方案 > 如何使用 Naked 在 Python 中正确捕获 Node js 脚本的错误?

问题描述

我正在使用此处提到的 Python 裸库来执行 Nodejs 脚本,该脚本也可在此处获得。关键是,每当我通过终端运行我的 python 脚本(完全取自上面的链接)时,我都可以看到 nodejs 脚本的输出。我将此 python 脚本包含在我的 Django 服务器中,并在进行 API 调用时运行它。

当页面验证失败时,我无法正确捕获错误。它总是返回“成功”。我觉得这是因为 Nodejs 是异步的。如果是这样,我怎样才能使 npm 网站中提到的函数 'amphtmlValidator.getInstance().then(function(validator)' 同步?我对 Nodejs 真的很陌生。

实际上,我只需要在 Django 中验证来自 python 脚本的 AMP 页面,而我发现的唯一方法是通过 python 调用节点脚本。一切正常,但我无法正确捕捉错误。请帮忙。

标签: pythonnode.jsdjangoamp-html

解决方案


我通过将“getInstance()”代码写入异步函数来解决这个问题,然后添加了 2 秒的睡眠,以确保所有数据都写入控制台。如果节点脚本中出现任何错误,我将手动添加关键字“ERROR”,否则我将添加“PASS”。

每当我使用 Python 执行此脚本时,我都会检查关键字。我知道这个答案不好,但我可以管理工作。这是我所做的:

节点脚本:

    function sleep(ms) {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

// async function that accepts a html file content and validates
async function validation(file) {
  //console.log(file);
  amphtmlValidator.getInstance().then(
    function(validator) {
      var result = validator.validateString(file);
      if (result.status === 'PASS') {
        console.log("PASS")
      } else {
        for (var ii = 0; ii < result.errors.length; ii++) {
          var error = result.errors[ii];
          var msg = 'ERROR : ' + 'line ' + error.line + ', col ' + error.col + ': ' + error.message;
          console.log(msg);
        }
      }
    });
  await sleep(2000);
}

Python:

response = muterun_js("validate.js", args)

if response:
  if "ERROR" in response.stdout.decode():
      print("validation failed")
  elif "PASS" in response.stdout.decode():
      print("success")

推荐阅读