【发布时间】:2019-07-21 08:55:30
【问题描述】:
我正在尝试从 node.js 应用程序执行机器学习脚本,使用子进程核心模块,如 here 所述
但是,我无法从 script.stdout.on 获得简单的输出。
我正在使用 Node v12.5.0 和 python 3.7.3
我制作了一个示例“hello world”脚本和 JS 函数来测试(如下所示),并从命令行运行脚本就好了。
这些是我的脚本:
test.py
import sys
print('hello world')
sys.stdout.flush()
JavaScript 测试函数
const { spawn } = require("child_process");
const pytest = spawn("python", ["./path/to/test.py"]);
console.log("firstPrint");
pytest.stdout.on("data", data => {
console.log("secondPrint");
console.log(data);
});
pytest.stdout.on("close", code => {
console.log(`script closed: ${code}`);
});
我的控制台输出是:
firstPrint
script closed: false
虽然应该是:
firstPrint
secondPrint
hello world
script closed: {code}
【问题讨论】:
-
脚本可能由于某些原因出错(例如,错误的路径)。我会添加一个
on('close') call topytest` 并仔细检查脚本是否正确执行。 -
@Mureinik 脚本退出,我更新了帖子。谢谢!
-
加
pytest.stderr.on('data', (data) => { console.log(`stderr: ${data}`); });看看有没有错误。 -
@dfsq 无法打开文件或目录错误。我尝试将文件移动到同一目录并使用“./test.py”、“/test.py”和“test.py”,仍然无法打开它。
-
检查文件权限,文件的用途和所属组?
标签: javascript python node.js