python-shell

Run Python scripts from Node.js with simple (but efficient) inter-process c...

README

python-shell


A simple way to run Python scripts from Node.js with basic but efficient inter-process communication and better error handling.

Features


+ Reliably spawn Python scripts in a child process
+ Built-in text, JSON and binary modes
+ Custom parsers and formatters
+ Simple and efficient data transfers through stdin and stdout streams
+ Extended stack traces when an error is thrown

Requirements

First make sure you are able to run python3 (Mac/Linux) or python (Windows) from the terminal. If you are not then you might need to add it to the PATH. If you want to use a version of python not in the PATH you should specify options.pythonPath.

Installation


  1. ```bash
  2. npm install python-shell
  3. ```

Documentation


Running python code:


  1. ```typescript
  2. import {PythonShell} from 'python-shell';

  3. PythonShell.runString('x=1+1;print(x)', null).then(messages=>{
  4.   console.log('finished');
  5. });
  6. ```

If the script exits with a non-zero code, an error will be thrown.

Note the use of imports! If you're not using typescript ಠ_ಠ you can still get imports to work with this guide.

Or you can use require like so:
  1. ```javascript
  2. let {PythonShell} = require('python-shell')
  3. ```

Running a Python script:


  1. ```typescript
  2. import {PythonShell} from 'python-shell';

  3. PythonShell.run('my_script.py', null).then(messages=>{
  4.   console.log('finished');
  5. });
  6. ```

If the script exits with a non-zero code, an error will be thrown.

Running a Python script with arguments and options:


  1. ```typescript
  2. import {PythonShell} from 'python-shell';

  3. let options = {
  4.   mode: 'text',
  5.   pythonPath: 'path/to/python',
  6.   pythonOptions: ['-u'], // get print results in real-time
  7.   scriptPath: 'path/to/my/scripts',
  8.   args: ['value1', 'value2', 'value3']
  9. };

  10. PythonShell.run('my_script.py', options).then(messages=>{
  11.   // results is an array consisting of messages collected during execution
  12.   console.log('results: %j', results);
  13. });
  14. ```

Exchanging data between Node and Python:


  1. ```typescript
  2. import {PythonShell} from 'python-shell';
  3. let pyshell = new PythonShell('my_script.py');

  4. // sends a message to the Python script via stdin
  5. pyshell.send('hello');

  6. pyshell.on('message', function (message) {
  7.   // received a message sent from the Python script (a simple "print" statement)
  8.   console.log(message);
  9. });

  10. // end the input stream and allow the process to exit
  11. pyshell.end(function (err,code,signal) {
  12.   if (err) throw err;
  13.   console.log('The exit code was: ' + code);
  14.   console.log('The exit signal was: ' + signal);
  15.   console.log('finished');
  16. });
  17. ```

Use .send(message) to send a message to the Python script. Attach the message event to listen to messages emitted from the Python script.

Use options.mode to quickly setup how data is sent and received between your Node and Python applications.

  use text mode for exchanging lines of text ending with a newline character.
  use json mode for exchanging JSON fragments
  use binary mode for anything else (data is sent and received as-is)

Stderr always uses text mode.

For more details and examples including Python source code, take a look at the tests.

Error Handling and extended stack traces


An error will be thrown if the process exits with a non-zero exit code. Additionally, if "stderr" contains a formatted Python traceback, the error is augmented with Python exception details including a concatenated stack trace.

Sample error with traceback (from test/python/error.py):

  1. ```
  2. Traceback (most recent call last):
  3.   File "test/python/error.py", line 6, in <module>
  4.     divide_by_zero()
  5.   File "test/python/error.py", line 4, in divide_by_zero
  6.     print 1/0
  7. ZeroDivisionError: integer division or modulo by zero
  8. ```

would result into the following error:

  1. ```typescript
  2. { [Error: ZeroDivisionError: integer division or modulo by zero]
  3.   traceback: 'Traceback (most recent call last):\n  File "test/python/error.py", line 6, in <module>\n    divide_by_zero()\n  File "test/python/error.py", line 4, in divide_by_zero\n    print 1/0\nZeroDivisionError: integer division or modulo by zero\n',
  4.   executable: 'python',
  5.   options: null,
  6.   script: 'test/python/error.py',
  7.   args: null,
  8.   exitCode: 1 }
  9. ```

and err.stack would look like this:

  1. ```
  2. Error: ZeroDivisionError: integer division or modulo by zero
  3.     at PythonShell.parseError (python-shell/index.js:131:17)
  4.     at ChildProcess.<anonymous> (python-shell/index.js:67:28)
  5.     at ChildProcess.EventEmitter.emit (events.js:98:17)
  6.     at Process.ChildProcess._handle.onexit (child_process.js:797:12)
  7.     ----- Python Traceback -----
  8.     File "test/python/error.py", line 6, in <module>
  9.       divide_by_zero()
  10.     File "test/python/error.py", line 4, in divide_by_zero
  11.       print 1/0
  12. ```

API Reference


PythonShell(script, options) constructor


Creates an instance of PythonShell and starts the Python process

script: the path of the script to execute
options: the execution options, consisting of:
  mode: Configures how data is exchanged when data flows through stdin and stdout. The possible values are:
    text: each line of data is emitted as a message (default)
    json: each line of data is parsed as JSON and emitted as a message
    binary: data is streamed as-is through stdout and stdin
  formatter: each message to send is transformed using this method, then appended with a newline
  parser: each line of data is parsed with this function and its result is emitted as a message
  stderrParser: each line of logs is parsed with this function and its result is emitted as a message
  encoding: the text encoding to apply on the child process streams (default: "utf8")
  pythonPath: The path where to locate the "python" executable. Default: "python3" ("python" for Windows)
  pythonOptions: Array of option switches to pass to "python"
  scriptPath: The default path where to look for scripts. Default is the current working directory.
  args: Array of arguments to pass to the script
stdoutSplitter: splits stdout into chunks, defaulting to splitting into newline-seperated lines
stderrSplitter: splits stderr into chunks, defaulting to splitting into newline-seperated lines

Other options are forwarded to child_process.spawn.

PythonShell instances have the following properties:
script: the path of the script to execute
command: the full command arguments passed to the Python executable
stdin: the Python stdin stream, used to send data to the child process
stdout: the Python stdout stream, used for receiving data from the child process
stderr: the Python stderr stream, used for communicating logs & errors
childProcess: the process instance created via child_process.spawn
terminated: boolean indicating whether the process has exited
exitCode: the process exit code, available after the process has ended

Example:

  1. ```typescript
  2. // create a new instance
  3. let shell = new PythonShell('script.py', options);
  4. ```

#defaultOptions


Configures default options for all new instances of PythonShell.

Example:

  1. ```typescript
  2. // setup a default "scriptPath"
  3. PythonShell.defaultOptions = { scriptPath: '../scripts' };
  4. ```

#run(script, options)


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:

  1. ```typescript
  2. // run a simple script
  3. PythonShell.run('script.py', null).then(results => {
  4.   // script finished
  5. });
  6. ```

#runString(code, options)


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:

  1. ```typescript
  2. // run some simple code
  3. PythonShell.runString('x=1;print(x)', null).then(messages=>{
  4.   // script finished
  5. });
  6. ```

#checkSyntax(code:string)


Checks the syntax of the code and returns a promise.
Promise is rejected if there is a syntax error.

#checkSyntaxFile(filePath:string)


Checks the syntax of the file and returns a promise.
Promise is rejected if there is a syntax error.

#getVersion(pythonPath?:string)


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

#getVersionSync(pythonPath?:string)


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

.send(message)


Sends a message to the Python script via stdin. The data is formatted according to the selected mode (text or JSON), or through a custom function when formatter is specified.

Example:

  1. ```typescript
  2. // send a message in text mode
  3. let shell = new PythonShell('script.py', { mode: 'text'});
  4. shell.send('hello world!');

  5. // send a message in JSON mode
  6. let shell = new PythonShell('script.py', { mode: 'json'});
  7. shell.send({ command: "do_stuff", args: [1, 2, 3] });
  8. ```

.end(callback)


Closes the stdin stream, allowing the Python script to finish and exit. The optional callback is invoked when the process is terminated.

.kill(signal)


Terminates the python script. A kill signal may be provided by signal, if signal is not specified SIGTERM is sent.

event: message


After the stdout stream is split into chunks by stdoutSplitter the chunks are parsed by the parser and a message event is emitted for each parsed chunk. This event is not emitted in binary mode.

Example:

  1. ```typescript
  2. // receive a message in text mode
  3. let shell = new PythonShell('script.py', { mode: 'text'});
  4. shell.on('message', function (message) {
  5.   // handle message (a line of text from stdout)
  6. });

  7. // receive a message in JSON mode
  8. let shell = new PythonShell('script.py', { mode: 'json'});
  9. shell.on('message', function (message) {
  10.   // handle message (a line of text from stdout, parsed as JSON)
  11. });
  12. ```

event: stderr


After the stderr stream is split into chunks by stderrSplitter the chunks are parsed by the parser and a message event is emitted for each parsed chunk. This event is not emitted in binary mode.

Example:

  1. ```typescript
  2. // receive a message in text mode
  3. let shell = new PythonShell('script.py', { mode: 'text'});
  4. shell.on('stderr', function (stderr) {
  5.   // handle stderr (a line of text from stderr)
  6. });
  7. ```

event: close


Fires when the process has been terminated, with an error or not.

event: pythonError


Fires when the process terminates with a non-zero exit code.

event: error


Fires when:
The process could not be spawned, or
The process could not be killed, or
Sending a message to the child process failed.

If the process could not be spawned please double-check that python can be launched from the terminal.

NewlineTransformer


A utility class for splitting stream data into newlines. Used as the default for stdoutSplitter and stderrSplitter if they are unspecified. You can use this class for any extra python streams if you'd like. For example:

  1. ```python
  2. # foo.py
  3. print('hello world', file=open(3, "w"))
  4. ```

  1. ```typescript
  2. import { PythonShell, NewlineTransformer, Options } from 'python-shell'

  3. const options: Options = {
  4.     'stdio':
  5.         ['pipe', 'pipe', 'pipe', 'pipe'] // stdin, stdout, stderr, custom
  6. }
  7. const pyshell = new PythonShell('foo.py', options)

  8. const customPipe = pyshell.childProcess.stdio[3]
  9. customPipe.pipe(new NewlineTransformer()).on('data', (customResult: Buffer) => {
  10.     console.log(customResult.toString())
  11. })
  12. ```

Used By:


Python-Shell is used by arepl-vscode, gitinspector, pyspreadsheet, AtlantOS Ocean Data QC and more!

License


The MIT License (MIT)

Copyright (c) 2014 Nicolas Mercier

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.