【问题标题】:Node.js child_process spawnSync catch errors from python scriptNode.js child_process spawnSync 从 python 脚本中捕获错误
【发布时间】: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


    【解决方案1】:

    child_process 可以在执行过程中监听错误,试试这个:

    const chid_proccess = require('child_process').spawn;
    
    
    let main_spawn_process = chid_proccess('run some foo')
    
    main_spawn_process.on('error', function(err) {
      console.log(err);
    }); 
    

    【讨论】:

    • 我需要它是同步的
    • 我已经尝试过这种方式,python错误和节点子进程生成的on('error')之间似乎没有标准。错误捕获仅与子进程中的模式环境本身有关。如果捕获python错误并使用前缀打印它们,并在on('data')中接收所有错误并检查它是否是带有前缀的错误来处理或抛出您自己的错误,这可能是正确的方法。
    猜你喜欢
    • 2017-03-02
    • 2017-05-18
    • 2020-10-08
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多