You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
4
4
5
5
## Features
6
6
7
7
+ Reliably spawn Python scripts in a child process
8
8
+ Text, JSON and binary modes
9
9
+ 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
11
11
12
12
## Installation
13
13
@@ -25,6 +25,8 @@ npm test
25
25
### Running a Python script:
26
26
27
27
```js
28
+
var PythonShell =require('python-shell');
29
+
28
30
PythonShell.run('my_script.py', function (err) {
29
31
if (err) throw err;
30
32
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
36
38
### Running a Python script with arguments and options:
37
39
38
40
```js
41
+
var PythonShell =require('python-shell');
42
+
39
43
var options = {
40
44
mode:'text',
41
45
pythonPath:'path/to/python',
@@ -44,34 +48,24 @@ var options = {
44
48
args: ['value1', 'value2', 'value3']
45
49
};
46
50
47
-
PythonShell.run('my_script.py', options, function (err) {
51
+
PythonShell.run('my_script.py', options, function (err, results) {
48
52
if (err) throw err;
53
+
// results is an array consisting of messages collected during execution
54
+
console.log('results: %j', results);
49
55
});
50
56
```
51
57
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
-
65
58
### Exchanging data between Node and Python:
66
59
67
60
```js
61
+
var PythonShell =require('python-shell');
68
62
var pyshell =newPythonShell('my_script.py');
69
63
70
-
//send a message to the Python script via stdin
64
+
//sends a message to the Python script via stdin
71
65
pyshell.send('hello');
72
66
73
67
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)
75
69
console.log(message);
76
70
});
77
71
@@ -84,13 +78,13 @@ pyshell.end(function (err) {
84
78
85
79
Use `.send(message)` to send a message to the Python script. Attach the `message` event to listen to messages emitted from the Python script.
86
80
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.
88
82
89
83
### Error Handling and extended stack traces
90
84
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.
92
86
93
-
Example error with traceback (from test/python/error.py):
87
+
Sample error with traceback (from test/python/error.py):
ZeroDivisionError: integer division or modulo by zero
101
95
```
102
-
would result into:
96
+
would result into the following error:
103
97
```js
104
98
{ [Error: ZeroDivisionError: integer division or modulo by zero]
105
99
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
123
117
print 1/0
124
118
```
125
119
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 =newPythonShell('script.py', options);
153
+
```
154
+
155
+
#### `#defaultOptions`
156
+
157
+
Configures default options for all new instances of PythonShell.
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 =newPythonShell('script.py', { mode:'text '});
189
+
shell.send('hello world!');
190
+
191
+
// send a message in JSON mode
192
+
var shell =newPythonShell('script.py', { mode:'json '});
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 =newPythonShell('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 =newPythonShell('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.
0 commit comments