Skip to content

Commit 7397599

Browse files
committed
improved documentation
1 parent d1d90c8 commit 7397599

File tree

1 file changed

+127
-22
lines changed

1 file changed

+127
-22
lines changed

README.md

Lines changed: 127 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
# python-shell
22

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

55
## Features
66

77
+ Reliably spawn Python scripts in a child process
88
+ Text, JSON and binary modes
99
+ Simple and efficient data transfers through stdin and stdout streams
10-
+ Extended stack traces in case an exception is thrown
10+
+ Extended stack traces when an error is thrown
1111

1212
## Installation
1313

@@ -25,6 +25,8 @@ npm test
2525
### Running a Python script:
2626

2727
```js
28+
var PythonShell = require('python-shell');
29+
2830
PythonShell.run('my_script.py', function (err) {
2931
if (err) throw err;
3032
console.log('finished');
@@ -36,6 +38,8 @@ If the script writes to stderr or exits with a non-zero code, an error will be t
3638
### Running a Python script with arguments and options:
3739

3840
```js
41+
var PythonShell = require('python-shell');
42+
3943
var options = {
4044
mode: 'text',
4145
pythonPath: 'path/to/python',
@@ -44,34 +48,24 @@ var options = {
4448
args: ['value1', 'value2', 'value3']
4549
};
4650

47-
PythonShell.run('my_script.py', options, function (err) {
51+
PythonShell.run('my_script.py', options, function (err, results) {
4852
if (err) throw err;
53+
// results is an array consisting of messages collected during execution
54+
console.log('results: %j', results);
4955
});
5056
```
5157

52-
The options are:
53-
54-
* `mode`: Configures how data is exchanged between the child process and its parent. The possible values are:
55-
* `text`: each line of data (ending with "\n") is emitted as a message (default)
56-
* `json`: each line of data (ending with "\n") is parsed as JSON and emitted as a message
57-
* `binary`: data is streamed as-is through `stdout` nd `stdin`
58-
* `pythonPath`: The path where to locate the "python" executable. Default: "python"
59-
* `pythonOptions`: Array of option switches to pass to "python"
60-
* `scriptPath`: The default path where to look for scripts. Default: "./python"
61-
* `args`: Array of arguments to pass to the script
62-
63-
Other options are forwarded to `child_process.spawn`.
64-
6558
### Exchanging data between Node and Python:
6659

6760
```js
61+
var PythonShell = require('python-shell');
6862
var pyshell = new PythonShell('my_script.py');
6963

70-
// send a message to the Python script via stdin
64+
// sends a message to the Python script via stdin
7165
pyshell.send('hello');
7266

7367
pyshell.on('message', function (message) {
74-
// received a message emitted from the script via stdout
68+
// received a message sent from the Python script (a simple "print" statement)
7569
console.log(message);
7670
});
7771

@@ -84,13 +78,13 @@ pyshell.end(function (err) {
8478

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

87-
For more details and examples, take a look at the unit tests.
81+
For more details and examples including Python source code, take a look at the tests.
8882

8983
### Error Handling and extended stack traces
9084

91-
An error will be thrown if the process exits with a non-zero exit code or if data has been written to stderr. Additionally, if "stderr" contains a standard Python traceback, the error is augmented with Python exception details including a concatenated stack trace.
85+
An error will be thrown if the process exits with a non-zero exit code or if data has been written to stderr. Additionally, if "stderr" contains a formatted Python traceback, the error is augmented with Python exception details including a concatenated stack trace.
9286

93-
Example error with traceback (from test/python/error.py):
87+
Sample error with traceback (from test/python/error.py):
9488
```
9589
Traceback (most recent call last):
9690
File "test/python/error.py", line 6, in <module>
@@ -99,7 +93,7 @@ Traceback (most recent call last):
9993
print 1/0
10094
ZeroDivisionError: integer division or modulo by zero
10195
```
102-
would result into:
96+
would result into the following error:
10397
```js
10498
{ [Error: ZeroDivisionError: integer division or modulo by zero]
10599
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',
@@ -123,6 +117,117 @@ Error: ZeroDivisionError: integer division or modulo by zero
123117
print 1/0
124118
```
125119

120+
## API Reference
121+
122+
#### `PythonShell(script, options)` constructor
123+
124+
Creates an instance of `PythonShell` and starts the Python process
125+
126+
* `script`: the path of the script to execute
127+
* `options`: the execution options, consisting of:
128+
* `mode`: Configures how data is exchanged when data flows through stdin and stdout. The possible values are:
129+
* `text`: each line of data (ending with "\n") is emitted as a message (default)
130+
* `json`: each line of data (ending with "\n") is parsed as JSON and emitted as a message
131+
* `binary`: data is streamed as-is through `stdout` and `stdin`
132+
* `pythonPath`: The path where to locate the "python" executable. Default: "python"
133+
* `pythonOptions`: Array of option switches to pass to "python"
134+
* `scriptPath`: The default path where to look for scripts. Default: "./python"
135+
* `args`: Array of arguments to pass to the script
136+
137+
Other options are forwarded to `child_process.spawn`.
138+
139+
PythonShell instances have the following properties:
140+
* `script`: the path of the script to execute
141+
* `command`: the full command arguments passed to the Python executable
142+
* `stdin`: the Python stdin stream, used to send data to the child process
143+
* `stdout`: the Python stdout stream, used for receiving data from the child process
144+
* `stderr`: the Python stderr stream, used for communicating errors
145+
* `childProcess`: the process instance created via `child_process.spawn`
146+
* `terminated`: boolean indicating whether the process has exited
147+
* `exitCode`: the process exit code, available after the process has ended
148+
149+
Example:
150+
```js
151+
// create a new instance
152+
var shell = new PythonShell('script.py', options);
153+
```
154+
155+
#### `#defaultOptions`
156+
157+
Configures default options for all new instances of PythonShell.
158+
159+
Example:
160+
```js
161+
// setup a default "scriptPath"
162+
PythonShell.defaultOptions = { scriptPath: '../scripts' };
163+
```
164+
165+
#### `#run(script, options, callback)`
166+
167+
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.
168+
169+
This method is also returning the `PythonShell` instance.
170+
171+
Example:
172+
```js
173+
// run a simple script
174+
PythonShell.run('script.py', function (err, results) {
175+
// script finished
176+
});
177+
```
178+
179+
#### `.send(message)`
180+
181+
Sends a message to the Python script via stdin. The data is formatted according to the selected mode (text or JSON). This method can be overridden in order to format the data in some other way.
182+
183+
This method should not be used in binary mode.
184+
185+
Example:
186+
```js
187+
// send a message in text mode
188+
var shell = new PythonShell('script.py', { mode: 'text '});
189+
shell.send('hello world!');
190+
191+
// send a message in JSON mode
192+
var shell = new PythonShell('script.py', { mode: 'json '});
193+
shell.send({ command: "do_stuff", args: [1, 2, 3] });
194+
```
195+
196+
#### `.receive(data)`
197+
198+
Parses incoming data from the Python script written via stdout and emits `message` events. The data is parsed as JSON if mode has been set to "json". This method is called automatically as data is being received from stdout and can be overridden to parse the data differently.
199+
200+
#### `.end(callback)`
201+
202+
Closes the stdin stream, allowing the Python script to finish and exit. The optional callback is invoked when the process is terminated.
203+
204+
#### event: `message`
205+
206+
Fires when a chunk of data is parsed from the stdout stream via the `receive` method. This event is not emitted in binary mode.
207+
208+
Example:
209+
```js
210+
// receive a message in text mode
211+
var shell = new PythonShell('script.py', { mode: 'text '});
212+
shell.on('message', function (message) {
213+
// handle message (a line of text from stdout)
214+
});
215+
216+
// receive a message in JSON mode
217+
var shell = new PythonShell('script.py', { mode: 'json '});
218+
shell.on('message', function (message) {
219+
// handle message (a line of text from stdout, parsed as JSON)
220+
});
221+
```
222+
223+
#### event: `close`
224+
225+
Fires when the process has been terminated, with an error or not.
226+
227+
#### event: `error`
228+
229+
Fires when the process terminates with a non-zero exit code, or if data is written to the stderr stream.
230+
126231
## License
127232

128233
The MIT License (MIT)

0 commit comments

Comments
 (0)