从 Python 脚本的 Node.js 中的 spawn 进程中获取数据
Getting data from spawn process in Node.js from a Python script
我是 运行 来自 Node.js 应用程序的 Python 脚本,使用导入而不是 require,代码如下:
import { spawn } from "child_process";
async foo(): Promise<fooResponse> {
try {
let dataToSend: string = "";
const pythonProcess = spawn('python', [__dirname + "\script.py"],{cwd:__dirname});
pythonProcess.stdout.on('data', function (data) {
dataToSend = data.toString();
});
return {
message: dataToSend,
};
} catch (e) {
if (e instanceof Error) {
return {
message: "Error",
};
}
return {
message: "Error",
};
}
}
}
在我的script.py里面我有这个:
print('Hello from python')
我需要 foo
return 是从 Python 脚本 return 编辑的 'Hello from python'
。如您所见,我尝试使用变量 dataToSend
但是当我 return 它时,它是空的。
从事件中导入 once
函数
import { once } from 'events'
然后用以下内容替换 .on
行:
dataToSend = (await once(pythonProcess.stdout, 'data')).toString()
我是 运行 来自 Node.js 应用程序的 Python 脚本,使用导入而不是 require,代码如下:
import { spawn } from "child_process";
async foo(): Promise<fooResponse> {
try {
let dataToSend: string = "";
const pythonProcess = spawn('python', [__dirname + "\script.py"],{cwd:__dirname});
pythonProcess.stdout.on('data', function (data) {
dataToSend = data.toString();
});
return {
message: dataToSend,
};
} catch (e) {
if (e instanceof Error) {
return {
message: "Error",
};
}
return {
message: "Error",
};
}
}
}
在我的script.py里面我有这个:
print('Hello from python')
我需要 foo
return 是从 Python 脚本 return 编辑的 'Hello from python'
。如您所见,我尝试使用变量 dataToSend
但是当我 return 它时,它是空的。
从事件中导入 once
函数
import { once } from 'events'
然后用以下内容替换 .on
行:
dataToSend = (await once(pythonProcess.stdout, 'data')).toString()