【发布时间】:2019-10-28 10:48:21
【问题描述】:
我正在使用 child_process spawnSync 方法来运行一些 python 脚本,它都可以正常工作,但到目前为止我无法捕捉 python 在 try/catch 块中抛出的错误,如果我也能捕捉到从 python 手动引发的错误,那就太好了.
示例:
Node.js
try {
const process =
await spawn('python3', [ Helpers.resourcesPath('pythonScripts/main.py'),
debug_mode,
lang
], { input: '"' + front_img + '""' + back_img + '"' });
const errorText = process.stderr.toString().trim();
if (errorText) {
return response.badRequest({
message: errorText
});
} else {
return response.success({
message: process.stdout.toString().trim()
});
}
} catch(e) {
return response.badRequest()
}
Python
try:
ocr = tool.image_to_string(Image.fromarray(img))
for key, words in languages.items():
result = [x.strip() for x in words.split(',')]
if any(x in ocr for x in result):
languageDetected = key
if languageDetected: break
if languageDetected:
return languageDetected
else:
# I want also to be able to get this as a error in node.js
raise Exception('Language not detected')
sys.exit(1)
except Exception as e:
print(str(e))
sys.exit()
在这个例子中,如果在 python 代码中的 catch(e) 中捕获了一个错误,它将返回到 process.stdout 而不是 process.stderr,我希望能够检查它是否返回了错误或node.js 中的良好响应。
如果我也能捕捉到这个在 node.js 中手动抛出的异常,那就太好了
raise Exception('Language not detected')
【问题讨论】:
标签: python node.js child-process spawn