|
| 1 | +var EventEmitter = require('events').EventEmitter; |
| 2 | +var path = require('path'); |
| 3 | +var util = require('util'); |
| 4 | +var spawn = require('child_process').spawn; |
| 5 | + |
| 6 | +function toArray(source) { |
| 7 | + if (typeof source === 'undefined' || source === null) { |
| 8 | + return []; |
| 9 | + } else if (!Array.isArray(source)) { |
| 10 | + return [source]; |
| 11 | + } |
| 12 | + return source; |
| 13 | +} |
| 14 | + |
| 15 | +function extend(obj) { |
| 16 | + Array.prototype.slice.call(arguments, 1).forEach(function (source) { |
| 17 | + if (source) { |
| 18 | + for (var key in source) { |
| 19 | + obj[key] = source[key]; |
| 20 | + } |
| 21 | + } |
| 22 | + }); |
| 23 | + return obj; |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * An interactive Python shell exchanging data through stdio |
| 28 | + * @param {string} script The python script to execute |
| 29 | + * @param {object} [options] The launch options (also passed to child_process.spawn) |
| 30 | + * @constructor |
| 31 | + */ |
| 32 | +var PythonShell = function (script, options) { |
| 33 | + var self = this; |
| 34 | + var errorData = ''; |
| 35 | + EventEmitter.call(this); |
| 36 | + |
| 37 | + options = extend({}, PythonShell.defaultOptions, options); |
| 38 | + var pythonPath = options.pythonPath || 'python'; |
| 39 | + var pythonOptions = toArray(options.pythonOptions); |
| 40 | + var scriptArgs = toArray(options.args); |
| 41 | + |
| 42 | + this.script = path.join(options.scriptPath || './python', script); |
| 43 | + this.command = pythonOptions.concat(this.script, scriptArgs); |
| 44 | + this.mode = options.mode || 'text'; |
| 45 | + this.terminated = false; |
| 46 | + this.childProcess = spawn(pythonPath, this.command, options); |
| 47 | + |
| 48 | + ['stdout', 'stdin', 'stderr'].forEach(function (name) { |
| 49 | + self[name] = self.childProcess[name]; |
| 50 | + self.mode !== 'binary' && self[name].setEncoding('utf8'); |
| 51 | + }); |
| 52 | + |
| 53 | + // listen for incoming data on stdout |
| 54 | + this.stdout.on('data', function (data) { |
| 55 | + self.mode !== 'binary' && self.receive(data); |
| 56 | + }); |
| 57 | + |
| 58 | + // listen to stderr and emit errors for incoming data |
| 59 | + this.stderr.on('data', function (data) { |
| 60 | + errorData += ''+data; |
| 61 | + }); |
| 62 | + |
| 63 | + this.childProcess.on('exit', function (code) { |
| 64 | + var err; |
| 65 | + if (errorData || code !== 0) { |
| 66 | + if (errorData) { |
| 67 | + err = self.parseError(errorData); |
| 68 | + } else { |
| 69 | + err = new Error('process exited with code ' + code); |
| 70 | + } |
| 71 | + err = extend(err, { |
| 72 | + executable: pythonPath, |
| 73 | + options: pythonOptions.length ? pythonOptions : null, |
| 74 | + script: self.script, |
| 75 | + args: scriptArgs.length ? scriptArgs : null, |
| 76 | + exitCode: code |
| 77 | + }); |
| 78 | + // do not emit error if only a callback is used |
| 79 | + if (self.listeners('ererrror').length || !self._endCallback) { |
| 80 | + self.emit('error', err); |
| 81 | + } |
| 82 | + } |
| 83 | + self.exitCode = code; |
| 84 | + self.terminated = true; |
| 85 | + self.emit('close'); |
| 86 | + self._endCallback && self._endCallback(err); |
| 87 | + }); |
| 88 | +}; |
| 89 | +util.inherits(PythonShell, EventEmitter); |
| 90 | + |
| 91 | +// allow global overrides for options |
| 92 | +PythonShell.defaultOptions = {}; |
| 93 | + |
| 94 | +/** |
| 95 | + * Runs a Python script and returns collected messages |
| 96 | + * @param {string} script The script to execute |
| 97 | + * @param {Object} options The execution options |
| 98 | + * @param {Function} callback The callback function to invoke with the script results |
| 99 | + * @return {PythonShell} The PythonShell instance |
| 100 | + */ |
| 101 | +PythonShell.run = function (script, options, callback) { |
| 102 | + if (typeof options === 'function') { |
| 103 | + callback = options; |
| 104 | + options = null; |
| 105 | + } |
| 106 | + |
| 107 | + var pyshell = new PythonShell(script, options); |
| 108 | + var output = []; |
| 109 | + |
| 110 | + return pyshell.on('message', function (message) { |
| 111 | + output.push(message); |
| 112 | + }).end(function (err) { |
| 113 | + if (err) return callback(err); |
| 114 | + return callback(null, output.length ? output : null); |
| 115 | + }); |
| 116 | +}; |
| 117 | + |
| 118 | +/** |
| 119 | + * Parses an error thrown from the Python process through stderr |
| 120 | + * @param {string|Buffer} data The stderr contents to parse |
| 121 | + * @return {Error} The parsed error with extended stack trace when traceback is available |
| 122 | + */ |
| 123 | +PythonShell.prototype.parseError = function (data) { |
| 124 | + var text = ''+data; |
| 125 | + var error; |
| 126 | + |
| 127 | + if (/^Traceback/.test(text)) { |
| 128 | + // traceback data is available |
| 129 | + var lines = (''+data).trim().split(/\n/g); |
| 130 | + var exception = lines.pop(); |
| 131 | + error = new Error(exception); |
| 132 | + error.traceback = data; |
| 133 | + // extend stack trace |
| 134 | + error.stack += '\n ----- Python Traceback -----\n '; |
| 135 | + error.stack += lines.slice(1).join('\n '); |
| 136 | + } else { |
| 137 | + // otherwise, create a simpler error with stderr contents |
| 138 | + error = new Error(text); |
| 139 | + } |
| 140 | + |
| 141 | + return error; |
| 142 | +}; |
| 143 | + |
| 144 | +/** |
| 145 | + * Sends a message to the Python shell through stdin |
| 146 | + * This method |
| 147 | + * Override this method to format data to be sent to the Python process |
| 148 | + * @param {string|Object} data The message to send |
| 149 | + * @returns {PythonShell} The same instance for chaining calls |
| 150 | + */ |
| 151 | +PythonShell.prototype.send = function (message) { |
| 152 | + if (this.mode === 'binary') { |
| 153 | + throw new Error('cannot send a message in binary mode, use stdin directly instead'); |
| 154 | + } else if (this.mode === 'json') { |
| 155 | + // write a JSON formatted message |
| 156 | + this.stdin.write(JSON.stringify(message) + '\n'); |
| 157 | + } else { |
| 158 | + // write text-based message (default) |
| 159 | + if (typeof message !== 'string') message = message.toString(); |
| 160 | + this.stdin.write(message + '\n'); |
| 161 | + } |
| 162 | + return this; |
| 163 | +}; |
| 164 | + |
| 165 | +/** |
| 166 | + * Parses data received from the Python shell stdout stream and emits "message" events |
| 167 | + * This method is not used in binary mode |
| 168 | + * Override this method to parse incoming data from the Python process into messages |
| 169 | + * @param {string|Buffer} data The data to parse into messages |
| 170 | + */ |
| 171 | +PythonShell.prototype.receive = function (data) { |
| 172 | + var self = this; |
| 173 | + var lines = (''+data).split(/\n/g); |
| 174 | + var lastLine = lines.pop(); |
| 175 | + |
| 176 | + // fix the first line with the remaining from the previous iteration of 'receive' |
| 177 | + lines[0] = (this._remaining || '') + lines[0]; |
| 178 | + // keep the remaining for the next iteration of 'receive' |
| 179 | + this._remaining = lastLine; |
| 180 | + |
| 181 | + lines.forEach(function (line) { |
| 182 | + if (self.mode === 'json') { |
| 183 | + try { |
| 184 | + self.emit('message', JSON.parse(line)); |
| 185 | + } catch (err) { |
| 186 | + self.emit('error', extend( |
| 187 | + new Error('invalid JSON message: ' + data), |
| 188 | + { inner: err, data: data} |
| 189 | + )); |
| 190 | + } |
| 191 | + } else { |
| 192 | + self.emit('message', line); |
| 193 | + } |
| 194 | + }); |
| 195 | +}; |
| 196 | + |
| 197 | +/** |
| 198 | + * Closes the stdin stream, which should cause the process to finish its work and close |
| 199 | + * @returns {PythonShell} The same instance for chaining calls |
| 200 | + */ |
| 201 | +PythonShell.prototype.end = function (callback) { |
| 202 | + this.childProcess.stdin.end(); |
| 203 | + this._endCallback = callback; |
| 204 | + return this; |
| 205 | +}; |
| 206 | + |
| 207 | +module.exports = PythonShell; |
0 commit comments