Bin*_*Gan 2 javascript python node.js
我试图从节点文件中调用python代码。
这是我的node.js代码:
var util = require("util");
var spawn = require("child_process").spawn;
var process = spawn('python',["workpad.py"]);
util.log('readingin')
process.stdout.on('data',function(data){
util.log(data);
});
Run Code Online (Sandbox Code Playgroud)
和我的python部分:
import sys
data = "test"
print(data)
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
在cmd窗口中,仅util.log('readingin')显示。我的代码有什么问题?
小智 8
我也遇到了同样的问题,我发现了这个:
var myPythonScript = "script.py";
// Provide the path of the python executable, if python is available as
// environment variable then you can use only "python"
var pythonExecutable = "python.exe";
// Function to convert an Uint8Array to a string
var uint8arrayToString = function(data){
return String.fromCharCode.apply(null, data);
};
const spawn = require('child_process').spawn;
const scriptExecution = spawn(pythonExecutable, [myPythonScript]);
// Handle normal output
scriptExecution.stdout.on('data', (data) => {
console.log(uint8arrayToString(data));
});
// Handle error output
scriptExecution.stderr.on('data', (data) => {
// As said before, convert the Uint8Array to a readable string.
console.log(uint8arrayToString(data));
});
scriptExecution.on('exit', (code) => {
console.log("Process quit with code : " + code);
});
Run Code Online (Sandbox Code Playgroud)
没有问题 ...
这是您的工作代码的一些细微调整(我将缓冲区转换为字符串,以便其易于阅读)
// spawn_python.js
var util = require("util");
var spawn = require("child_process").spawn;
var process = spawn('python',["python_launched_from_nodejs.py"]);
util.log('readingin')
process.stdout.on('data',function(chunk){
var textChunk = chunk.toString('utf8');// buffer to string
util.log(textChunk);
});
Run Code Online (Sandbox Code Playgroud)
这是你的蟒蛇
# python_launched_from_nodejs.py
import sys
data = "this began life in python"
print(data)
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
最后是运行的输出
node spawn_python.js
11 Dec 00:06:17 - readingin
11 Dec 00:06:17 - this began life in python
Run Code Online (Sandbox Code Playgroud)
节点-版本
v5.2.0