python - 如何使用 Naked 在 Python 中正确捕获 Node js 脚本的错误?
问题描述
我正在使用此处提到的 Python 裸库来执行 Nodejs 脚本,该脚本也可在此处获得。关键是,每当我通过终端运行我的 python 脚本(完全取自上面的链接)时,我都可以看到 nodejs 脚本的输出。我将此 python 脚本包含在我的 Django 服务器中,并在进行 API 调用时运行它。
当页面验证失败时,我无法正确捕获错误。它总是返回“成功”。我觉得这是因为 Nodejs 是异步的。如果是这样,我怎样才能使 npm 网站中提到的函数 'amphtmlValidator.getInstance().then(function(validator)' 同步?我对 Nodejs 真的很陌生。
实际上,我只需要在 Django 中验证来自 python 脚本的 AMP 页面,而我发现的唯一方法是通过 python 调用节点脚本。一切正常,但我无法正确捕捉错误。请帮忙。
解决方案
我通过将“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")
推荐阅读
- android-studio - 在 android studio 中实现 com.amulyakhare 库
- php - 如何获取PHP中关联数组的两个多维数组之间的差异?
- node.js - 应该通过正文发送 null 或空字符串值吗?
- python - 如何使用 python 收集获取 url 并移动到详细的链接数据
- dialogflow-es - Dialogflow Essentials“培训”几天不工作。有什么解决方法吗?
- sql - 如何以逗号 (,) 字符分隔的字符串形式返回 XML 嵌套节点的行
- flutter - Flutter/Dart 中的多行字符串到单行字符串
- create-react-app - 如何修复 create-react-app 中的 immer.js 问题?
- microsoft-graph-api - 如何在 o365 Graph API 中获取访问令牌以进行投诉
- javascript - 发送的 SuiteCRM 电子邮件由收件人接收一次,但电子邮件将在已发送项目上显示两次