从NodeJS执行python命令行工具

时间:2018-06-22 09:41:35

标签: javascript python node.js command

从nodejs到python执行命令行工具的最佳方法是什么?我正在开发可生成区块链证书的应用。

https://github.com/blockchain-certificates/cert-tools

这是基于python的命令行工具,您可以在其中生成区块链证书。我已经按照步骤操作,并且在虚拟环境中一切正常。但是现在我想知道如何在应用程序中实现它,在这里我可以运行NodeJS外部的命令行工具。这可能吗?我发现了一些库,您可以在其中运行来自nodejs的python脚本。示例我使用了python shell。每当我运行安装脚本时,都会丢失文件错误。

有人可以指导我解决该问题的最佳方法是什么。提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以在节点中使用python shell,就像下面这样使用它:

var PythonShell = require('python-shell');

PythonShell.run('my_script.py', function (err) {
  if (err) throw err;
  console.log('finished');
});

有关更多文档,请访问他们的github存储库,希望我能提供帮助:)

答案 1 :(得分:0)

您应该只能够使用child_process.exec()函数执行命令。

确保仅在python脚本完成后才使用该文件。

child_process.exec('py path/to/script.py arg1 arg2', (err, stdout, stderr) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
  // check if generated file exists
  let fileExists = require("fs").existsSync("/path/to/generated/file");
  if (fileExists) {
    // do something with the file
  }
});