我想将命令传递给 python 子进程,然后得到结果。我会使用 exec,但我想让子进程保持打开状态,这样我就不必每次执行新命令时都打开它。这是我目前什么都不做的代码:
var connect = require('connect'),
io = require("socket.io").listen(1032),
util = require("util"),
child = require('child_process'),
python = child.spawn("python");
var app = connect()
.use(connect.static(__dirname + '/www'))
.use(connect.logger('dev'))
.listen(3000);
io.sockets.on('connection', function (socket) {
console.log("Socket " + socket.id + " opened");
python.stdout.on('data', function (data) {
console.log("computed", data.toString("utf-8"));
socket.emit("python", { result : data.toString("utf-8") });
});
socket.on('python', function (data) {
console.log("received data" + data.cmd);
python.stdin.resume();
python.stdin.write(data.cmd);
python.stdin.end();
});
});