Skip to content

Commit 17d4942

Browse files
committed
feat: promisify the "run" command
1 parent 502bb3d commit 17d4942

File tree

2 files changed

+13
-11
lines changed

2 files changed

+13
-11
lines changed

index.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -310,19 +310,24 @@ export class PythonShell extends EventEmitter {
310310
* @param {string} scriptPath The path to the script to execute
311311
* @param {Options} options The execution options
312312
* @param {Function} callback The callback function to invoke with the script results
313-
* @return {PythonShell} The PythonShell instance
313+
* @return {Promise} the output from the python script
314314
*/
315315
static run(scriptPath: string, options?: Options, callback?: (err?: PythonShellError, output?: any[]) => any) {
316316
let pyshell = new PythonShell(scriptPath, options);
317317
let output = [];
318318

319-
return pyshell.on('message', function (message) {
320-
output.push(message);
321-
}).end(function (err) {
322-
return callback(err ? err : null, output.length ? output : null);
319+
return new Promise((resolve, reject) => {
320+
return pyshell.on('message', function (message) {
321+
output.push(message);
322+
}).end(function (err) {
323+
if(err) reject(err);
324+
else resolve(output);
325+
return callback(err ? err : null, output.length ? output : null);
326+
});
323327
});
324328
};
325329

330+
326331
/**
327332
* Runs the inputted string of python code and returns collected messages. DO NOT ALLOW UNTRUSTED USER INPUT HERE!
328333
* @param {string} code The python code to execute

test/test-python-shell.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -250,8 +250,8 @@ describe('PythonShell', function () {
250250
};
251251
})
252252

253-
it('should run PythonShell normally without access to std streams', function (done) {
254-
var pyshell = PythonShell.run('exit-code.py', {
253+
it('should run PythonShell normally without access to std streams', async function (done) {
254+
var pyshell = await PythonShell.run('exit-code.py', {
255255
// 3 different ways of assigning values to the std streams in child_process.spawn()
256256
// * ignore - pipe to /dev/null
257257
// * inherit - inherit fd from parent process;
@@ -263,10 +263,7 @@ describe('PythonShell', function () {
263263
args: "0"
264264
}, done);
265265

266-
should(pyshell.stdin).be.eql(null);
267-
should(pyshell.stdout).be.eql(null);
268-
should(pyshell.stderr).be.eql(null);
269-
should.throws(() => { pyshell.send("asd") });
266+
should(pyshell).be.eql([]);
270267
});
271268
});
272269

0 commit comments

Comments
 (0)