This repository was archived by the owner on Oct 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec.js
More file actions
110 lines (82 loc) · 2 KB
/
Copy pathexec.js
File metadata and controls
110 lines (82 loc) · 2 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"use strict";
var _ = require("lodash"),
Q = require("q"),
spawn = require('child_process').spawn;
/**
*
* Convert to variables
*
* @param {Object} variables
* @return {Array}
*
*/
var toVariables = function(variables){
variables = variables || {};
var vars = [];
_.each(variables, function(value, name){
if(typeof(value) == "number"){
vars.push(
_.template("<%= name %> = <%= value %>", { name: name, value: value }));
}
else{
vars.push(
_.template("<%= name %> = '<%= value %>'", { name: name, value: value }));
}
});
return vars;
};
/**
*
* Manages the execution of the python process. Once the code is executed the
* promise is resolved with the stdout of the process.
*
* @param {String} code
* @param {Object} options
*
* @return {Promise}
*
*/
var exec = function(code, options){
options = options || {};
options.bin = options.bin || "python";
options.vars = options.vars || {};
options.env = _.extend({},
{
/// set the env PYTHONPATH
PYTHONPATH: ""
},
process.env,
options.env);
var dfd = Q.defer(),
output = [];
/// create the python process
var python = spawn(options.bin, [], { env: options.env });
/// initialize the process IO
python.stdin.setEncoding('utf8');
python.stdout.setEncoding('utf8');
/// wait for stdout data
python.stdout.on('data', function(data){
output.push(data);
});
/// if some error is thrown reject the promise
python.stderr.on('data', function(data){
dfd.reject(data.toString());
});
python.stdout.on('close', function(code){
var result = output.join().trim();
/// resolve the output
dfd.resolve(result);
});
/// convert code into string
if(code instanceof Array){
code = code.join("\n");
}
/// append variables to the top of the code
code = toVariables(options.vars).join("\n") + "\n" + code;
/// send the python instruction
python.stdin.write(code);
/// terminate the stdin will terminate the process
python.stdin.end();
return dfd.promise;
};
module.exports = exec;