v5 release by Almenon · Pull Request #282 · extrabacon/python-shell · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
29 changes: 11 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ npm install python-shell
```typescript
import {PythonShell} from 'python-shell';

PythonShell.runString('x=1+1;print(x)', null, function (err) {
if (err) throw err;
PythonShell.runString('x=1+1;print(x)', null).then(messages=>{
console.log('finished');
});
```
Expand All @@ -47,8 +46,7 @@ let {PythonShell} = require('python-shell')
```typescript
import {PythonShell} from 'python-shell';

PythonShell.run('my_script.py', null, function (err) {
if (err) throw err;
PythonShell.run('my_script.py', null).then(messages=>{
console.log('finished');
});
```
Expand All @@ -68,8 +66,7 @@ let options = {
args: ['value1', 'value2', 'value3']
};

PythonShell.run('my_script.py', options, function (err, results) {
if (err) throw err;
PythonShell.run('my_script.py', options).then(messages=>{
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
Expand Down Expand Up @@ -205,32 +202,28 @@ Example:
PythonShell.defaultOptions = { scriptPath: '../scripts' };
```

#### `#run(script, options, callback)`

Runs the Python script and invokes `callback` with the results. The callback contains the execution error (if any) as well as an array of messages emitted from the Python script.
#### `#run(script, options)`

This method is also returning the `PythonShell` instance.
Runs the Python script and returns a promise. When you handle the promise the argument will be an array of messages emitted from the Python script.

Example:

```typescript
// run a simple script
PythonShell.run('script.py', null, function (err, results) {
PythonShell.run('script.py', null).then(results => {
// script finished
});
```

#### `#runString(code, options, callback)`
#### `#runString(code, options)`

Runs the Python code and invokes `callback` with the results. The callback contains the execution error (if any) as well as an array of messages emitted from the Python script.

This method is also returning the `PythonShell` instance.
Runs the Python script and returns a promise. When you handle the promise the argument will be an array of messages emitted from the Python script.

Example:

```typescript
// run a simple script
PythonShell.runString('x=1;print(x)', null, function (err, results) {
// run some simple code
PythonShell.runString('x=1;print(x)', null).then(messages=>{
// script finished
});
```
Expand All @@ -247,7 +240,7 @@ Promise is rejected if there is a syntax error.

#### `#getVersion(pythonPath?:string)`

Returns the python version. Optional pythonPath param to get the version
Returns the python version as a promise. Optional pythonPath param to get the version
of a specific python interpreter.

#### `#getVersionSync(pythonPath?:string)`
Expand Down
68 changes: 27 additions & 41 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ export class PythonShellError extends Error {
exitCode?: number;
}

export class PythonShellErrorWithLogs extends PythonShellError {
logs: any[]
}

/**
* Takes in a string stream and emits batches seperated by newlines
*/
Expand Down Expand Up @@ -306,62 +310,44 @@ export class PythonShell extends EventEmitter {
}

/**
* Runs a Python script and returns collected messages
* @param {string} scriptPath The path to the script to execute
* @param {Options} options The execution options
* @param {Function} (deprecated argument) callback The callback function to invoke with the script results
* @return {Promise<string[]> | PythonShell} the output from the python script
* Runs a Python script and returns collected messages as a promise.
* If the promise is rejected, the err will probably be of type PythonShellErrorWithLogs
* @param scriptPath The path to the script to execute
* @param options The execution options
*/
static run(scriptPath: string, options?: Options, callback?: (err?: PythonShellError, output?: any[]) => any) {

if(callback) {
console.warn('PythonShell.run() callback is deprecated. Use PythonShell.run() promise instead.')

return this.runLegacy(scriptPath, options, callback);
}
else {
return new Promise((resolve, reject) => {
let pyshell = new PythonShell(scriptPath, options);
let output = [];

pyshell.on('message', function (message) {
output.push(message);
}).end(function (err) {
if(err) reject(err);
else resolve(output);
});
static run(scriptPath: string, options?: Options): Promise<any[]> {
return new Promise((resolve, reject) => {
let pyshell = new PythonShell(scriptPath, options);
let output = [];

pyshell.on('message', function (message) {
output.push(message);
}).end(function (err) {
if(err){
(err as PythonShellErrorWithLogs).logs = output
reject(err);
}
else resolve(output);
});
}
};

private static runLegacy(scriptPath: string, options?: Options, callback?: (err?: PythonShellError, output?: any[]) => any) {
let pyshell = new PythonShell(scriptPath, options);
let output = [];

return pyshell.on('message', function (message) {
output.push(message);
}).end(function (err) {
return callback(err ? err : null, output.length ? output : null);
});
};



/**
* Runs the inputted string of python code and returns collected messages. DO NOT ALLOW UNTRUSTED USER INPUT HERE!
* @param {string} code The python code to execute
* @param {Options} options The execution options
* @param {Function} callback The callback function to invoke with the script results
* @return {PythonShell} The PythonShell instance
* Runs the inputted string of python code and returns collected messages as a promise. DO NOT ALLOW UNTRUSTED USER INPUT HERE!
* @param code The python code to execute
* @param options The execution options
* @return a promise with the output from the python script
*/
static runString(code: string, options?: Options, callback?: (err: PythonShellError, output?: any[]) => any) {
static runString(code: string, options?: Options) {

// put code in temp file
const randomInt = getRandomInt();
const filePath = tmpdir + sep + `pythonShellFile${randomInt}.py`
writeFileSync(filePath, code);

return PythonShell.run(filePath, options, callback);
return PythonShell.run(filePath, options);
};

static getVersion(pythonPath?: string) {
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
{
"name": "python-shell",
"version": "4.0.0",
"version": "5.0.0",
"description": "Run Python scripts from Node.js with simple (but efficient) inter-process communication through stdio",
"keywords": [
"python"
],
"scripts": {
"test": "tsc -p ./ && mocha -r ts-node/register",
"appveyorTest": "tsc -p ./ && nyc mocha --reporter mocha-appveyor-reporter test/*.js",
"compile": "tsc -watch -p ./"
"compile": "tsc -watch -p ./",
"compileOnce": "tsc -p ./"
},
"devDependencies": {
"@types/mocha": "^8.2.1",
Expand Down
55 changes: 27 additions & 28 deletions test/test-python-shell.ts