forked from 73rhodes/node-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython.js
More file actions
60 lines (49 loc) · 1.47 KB
/
python.js
File metadata and controls
60 lines (49 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
var util = require('util');
var spawn = require('child_process').spawn;
var child = spawn('python',['-u','-i']);
var cmdQueue = new Array();
child.stdout.on('data', handleStdout);
child.stderr.on('data', handleStderr);
child.on('exit', handleExit);
function handleStdout(data) {
var datastr = data.toString('utf8');
var finished = false;
if (datastr.match(/Command Start\n/)) {
datastr = datastr.replace(/Command Start\n/,'');
}
if (datastr.match(/Command End\n/)) {
datastr = datastr.replace(/Command End\n/,'');
finished = true;
}
if (cmdQueue.length > 0) {
cmdQueue[0].data+=datastr;
}
if (finished) {
cmd = cmdQueue.shift();
if (cmd && cmd.command) {
if (undefined != typeof cmd.callback) {
cmd.callback(null, cmd.data);
processQueue();
}
}
}
};
function handleStderr(data) {
processQueue();
};
function processQueue() {
if (cmdQueue.length > 0 && cmdQueue[0].state === 'pending') {
cmdQueue[0].state = 'processing';
child.stdin.write(cmdQueue[0].command, encoding='utf8');
}
};
function handleExit(code) {
console.log('child process exited with code ' + code);
process.exit();
};
this.shell = function (command, callback) {
command = 'print "Command Start"; ' + command + '\nprint "Command End"';
if (command.charAt[command.length-1]!='\n') command += '\n';
cmdQueue.push({'command':command, 'callback':callback, 'data': '', state: 'pending'});
processQueue();
};