added all files to project

This commit is contained in:
2022-03-10 10:36:59 +01:00
parent 09dd957b33
commit 46a936d7de
25351 changed files with 3883356 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
## 1.0.4
* added getVersionSync
## 0.0.3
* fixed buffering in `PythonShell.receive`, fixing [#1](https://github.com/extrabacon/python-shell/issues/1)
## 0.0.2
* improved documentation
## 0.0.1
* initial version
* independent module moved from [extrabacon/pyspreadsheet](https://github.com/extrabacon/pyspreadsheet)
+357
View File
@@ -0,0 +1,357 @@
# [python-shell](https://www.npmjs.com/package/python-shell) [![Build status](https://ci.appveyor.com/api/projects/status/m8e3h53vvxg5wb2q?svg=true)](https://ci.appveyor.com/project/Almenon/python-shell) [![codecov](https://codecov.io/gh/extrabacon/python-shell/branch/master/graph/badge.svg)](https://codecov.io/gh/extrabacon/python-shell)
<!-- chage above url accroding to repo -->
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
## Installation
```bash
npm install python-shell
```
To run the tests:
```bash
npm test
```
## Documentation
### Running python code:
```typescript
import {PythonShell} from 'python-shell';
PythonShell.runString('x=1+1;print(x)', null, function (err) {
if (err) throw err;
console.log('finished');
});
```
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](https://github.com/extrabacon/python-shell/issues/148#issuecomment-419120209).
Or you can use require like so:
```javascript
let {PythonShell} = require('python-shell')
```
### Running a Python script:
```typescript
import {PythonShell} from 'python-shell';
PythonShell.run('my_script.py', null, function (err) {
if (err) throw err;
console.log('finished');
});
```
If the script exits with a non-zero code, an error will be thrown.
### Running a Python script with arguments and options:
```typescript
import {PythonShell} from 'python-shell';
let options = {
mode: 'text',
pythonPath: 'path/to/python',
pythonOptions: ['-u'], // get print results in real-time
scriptPath: 'path/to/my/scripts',
args: ['value1', 'value2', 'value3']
};
PythonShell.run('my_script.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
```
### Exchanging data between Node and Python:
```typescript
import {PythonShell} from 'python-shell';
let pyshell = new PythonShell('my_script.py');
// sends a message to the Python script via stdin
pyshell.send('hello');
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err,code,signal) {
if (err) throw err;
console.log('The exit code was: ' + code);
console.log('The exit signal was: ' + signal);
console.log('finished');
console.log('finished');
});
```
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
* use `json` mode for exchanging JSON fragments
* use `binary` mode for anything else (data is sent and received as-is)
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):
```
Traceback (most recent call last):
File "test/python/error.py", line 6, in <module>
divide_by_zero()
File "test/python/error.py", line 4, in divide_by_zero
print 1/0
ZeroDivisionError: integer division or modulo by zero
```
would result into the following error:
```typescript
{ [Error: ZeroDivisionError: integer division or modulo by zero]
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',
executable: 'python',
options: null,
script: 'test/python/error.py',
args: null,
exitCode: 1 }
```
and `err.stack` would look like this:
```
Error: ZeroDivisionError: integer division or modulo by zero
at PythonShell.parseError (python-shell/index.js:131:17)
at ChildProcess.<anonymous> (python-shell/index.js:67:28)
at ChildProcess.EventEmitter.emit (events.js:98:17)
at Process.ChildProcess._handle.onexit (child_process.js:797:12)
----- Python Traceback -----
File "test/python/error.py", line 6, in <module>
divide_by_zero()
File "test/python/error.py", line 4, in divide_by_zero
print 1/0
```
## 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 (ending with "\n") is emitted as a message (default)
* `json`: each line of data (ending with "\n") 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 "\n"
* `parser`: each line of data (ending with "\n") is parsed with this function and its result is emitted as a message
* `stderrParser`: each line of logs (ending with "\n") 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: "python"
* `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
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:
```typescript
// create a new instance
let shell = new PythonShell('script.py', options);
```
#### `#defaultOptions`
Configures default options for all new instances of PythonShell.
Example:
```typescript
// setup a default "scriptPath"
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.
This method is also returning the `PythonShell` instance.
Example:
```typescript
// run a simple script
PythonShell.run('script.py', null, function (err, results) {
// script finished
});
```
#### `#runString(code, options, callback)`
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.
Example:
```typescript
// run a simple script
PythonShell.runString('x=1;print(x)', null, function (err, results) {
// script finished
});
```
#### `#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. 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:
```typescript
// send a message in text mode
let shell = new PythonShell('script.py', { mode: 'text '});
shell.send('hello world!');
// send a message in JSON mode
let shell = new PythonShell('script.py', { mode: 'json '});
shell.send({ command: "do_stuff", args: [1, 2, 3] });
```
#### `.receive(data)`
Parses incoming data from the Python script written via stdout and emits `message` events. This method is called automatically as data is being received from stdout.
#### `.receiveStderr(data)`
Parses incoming logs from the Python script written via stderr and emits `stderr` events. This method is called automatically as data is being received from stderr.
#### `.end(callback)`
Closes the stdin stream, allowing the Python script to finish and exit. The optional callback is invoked when the process is terminated.
#### `.terminate(signal)`
Terminates the python script, the optional end callback is invoked if specified. A kill signal may be provided by `signal`, if `signal` is not specified SIGTERM is sent.
#### event: `message`
Fires when a chunk of data is parsed from the stdout stream via the `receive` method. If a `parser` method is specified, the result of this function will be the message value. This event is not emitted in binary mode.
Example:
```typescript
// receive a message in text mode
let shell = new PythonShell('script.py', { mode: 'text '});
shell.on('message', function (message) {
// handle message (a line of text from stdout)
});
// receive a message in JSON mode
let shell = new PythonShell('script.py', { mode: 'json '});
shell.on('message', function (message) {
// handle message (a line of text from stdout, parsed as JSON)
});
```
#### event: `stderr`
Fires when a chunk of logs is parsed from the stderr stream via the `receiveStderr` method. If a `stderrParser` method is specified, the result of this function will be the message value. This event is not emitted in binary mode.
Example:
```typescript
// receive a message in text mode
let shell = new PythonShell('script.py', { mode: 'text '});
shell.on('stderr', function (stderr) {
// handle stderr (a line of text from stderr)
});
```
#### event: `close`
Fires when the process has been terminated, with an error or not.
#### event: `error`
Fires when the process terminates with a non-zero exit code.
## Used By:
Python-Shell is used by [arepl-vscode](https://github.com/almenon/arepl-vscode), [gitinspector](https://github.com/ejwa/gitinspector), [pyspreadsheet](https://github.com/extrabacon/pyspreadsheet), 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.
+141
View File
@@ -0,0 +1,141 @@
/// <reference types="node" />
import { EventEmitter } from 'events';
import { ChildProcess, SpawnOptions } from 'child_process';
import { Readable, Writable } from 'stream';
export interface Options extends SpawnOptions {
mode?: 'text' | 'json' | 'binary';
formatter?: (param: string) => any;
parser?: (param: string) => any;
stderrParser?: (param: string) => any;
encoding?: string;
pythonPath?: string;
/**
* see https://docs.python.org/3.7/using/cmdline.html
*/
pythonOptions?: string[];
/**
* overrides scriptPath passed into PythonShell constructor
*/
scriptPath?: string;
/**
* arguments to your program
*/
args?: string[];
}
export declare class PythonShellError extends Error {
traceback: string | Buffer;
exitCode?: number;
}
/**
* An interactive Python shell exchanging data through stdio
* @param {string} script The python script to execute
* @param {object} [options] The launch options (also passed to child_process.spawn)
* @constructor
*/
export declare class PythonShell extends EventEmitter {
scriptPath: string;
command: string[];
mode: string;
formatter: (param: string | Object) => any;
parser: (param: string) => any;
stderrParser: (param: string) => any;
terminated: boolean;
childProcess: ChildProcess;
stdin: Writable;
stdout: Readable;
stderr: Readable;
exitSignal: string;
exitCode: number;
private stderrHasEnded;
private stdoutHasEnded;
private _remaining;
private _endCallback;
static defaultPythonPath: string;
static defaultOptions: Options;
/**
* spawns a python process
* @param scriptPath path to script. Relative to current directory or options.scriptFolder if specified
* @param options
*/
constructor(scriptPath: string, options?: Options);
static format: {
text: (data: any) => string;
json: (data: any) => string;
};
static parse: {
text: (data: any) => string;
json: (data: string) => any;
};
/**
* checks syntax without executing code
* @param {string} code
* @returns {Promise} rejects w/ stderr if syntax failure
*/
static checkSyntax(code: string): Promise<{}>;
static getPythonPath(): string;
/**
* checks syntax without executing code
* @param {string} filePath
* @returns {Promise} rejects w/ stderr if syntax failure
*/
static checkSyntaxFile(filePath: string): Promise<string>;
/**
* 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} callback The callback function to invoke with the script results
* @return {PythonShell} The PythonShell instance
*/
static run(scriptPath: string, options?: Options, callback?: (err?: PythonShellError, output?: any[]) => any): PythonShell;
/**
* 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
*/
static runString(code: string, options?: Options, callback?: (err: PythonShellError, output?: any[]) => any): PythonShell;
static getVersion(pythonPath?: string): Promise<{
stdout: string;
stderr: string;
}>;
static getVersionSync(pythonPath?: string): string;
/**
* Parses an error thrown from the Python process through stderr
* @param {string|Buffer} data The stderr contents to parse
* @return {Error} The parsed error with extended stack trace when traceback is available
*/
private parseError;
/**
* Sends a message to the Python shell through stdin
* Override this method to format data to be sent to the Python process
* @param {string|Object} data The message to send
* @returns {PythonShell} The same instance for chaining calls
*/
send(message: string | Object): this;
/**
* Parses data received from the Python shell stdout stream and emits "message" events
* This method is not used in binary mode
* Override this method to parse incoming data from the Python process into messages
* @param {string|Buffer} data The data to parse into messages
*/
receive(data: string | Buffer): this;
/**
* Parses data received from the Python shell stderr stream and emits "stderr" events
* This method is not used in binary mode
* Override this method to parse incoming logs from the Python process into messages
* @param {string|Buffer} data The data to parse into messages
*/
receiveStderr(data: string | Buffer): this;
private receiveInternal;
/**
* Closes the stdin stream, which should cause the process to finish its work and close
* @returns {PythonShell} The same instance for chaining calls
*/
end(callback: (err: PythonShellError, exitCode: number, exitSignal: string) => any): this;
/**
* Closes the stdin stream, which should cause the process to finish its work and close
* @returns {PythonShell} The same instance for chaining calls
*/
terminate(signal?: string): this;
}
+380
View File
@@ -0,0 +1,380 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const child_process_1 = require("child_process");
const os_1 = require("os");
const path_1 = require("path");
const fs_1 = require("fs");
const util_1 = require("util");
function toArray(source) {
if (typeof source === 'undefined' || source === null) {
return [];
}
else if (!Array.isArray(source)) {
return [source];
}
return source;
}
/**
* adds arguments as properties to obj
*/
function extend(obj, ...args) {
Array.prototype.slice.call(arguments, 1).forEach(function (source) {
if (source) {
for (let key in source) {
obj[key] = source[key];
}
}
});
return obj;
}
/**
* gets a random int from 0-10000000000
*/
function getRandomInt() {
return Math.floor(Math.random() * 10000000000);
}
class PythonShellError extends Error {
}
exports.PythonShellError = PythonShellError;
/**
* An interactive Python shell exchanging data through stdio
* @param {string} script The python script to execute
* @param {object} [options] The launch options (also passed to child_process.spawn)
* @constructor
*/
class PythonShell extends events_1.EventEmitter {
/**
* spawns a python process
* @param scriptPath path to script. Relative to current directory or options.scriptFolder if specified
* @param options
*/
constructor(scriptPath, options) {
super();
/**
* returns either pythonshell func (if val string) or custom func (if val Function)
*/
function resolve(type, val) {
if (typeof val === 'string') {
// use a built-in function using its name
return PythonShell[type][val];
}
else if (typeof val === 'function') {
// use a custom function
return val;
}
}
if (scriptPath.trim().length == 0)
throw Error("scriptPath cannot be empty! You must give a script for python to run");
let self = this;
let errorData = '';
events_1.EventEmitter.call(this);
options = extend({}, PythonShell.defaultOptions, options);
let pythonPath;
if (!options.pythonPath) {
pythonPath = PythonShell.defaultPythonPath;
}
else
pythonPath = options.pythonPath;
let pythonOptions = toArray(options.pythonOptions);
let scriptArgs = toArray(options.args);
this.scriptPath = path_1.join(options.scriptPath || '', scriptPath);
this.command = pythonOptions.concat(this.scriptPath, scriptArgs);
this.mode = options.mode || 'text';
this.formatter = resolve('format', options.formatter || this.mode);
this.parser = resolve('parse', options.parser || this.mode);
this.stderrParser = resolve('parse', options.stderrParser || this.mode);
this.terminated = false;
this.childProcess = child_process_1.spawn(pythonPath, this.command, options);
['stdout', 'stdin', 'stderr'].forEach(function (name) {
self[name] = self.childProcess[name];
self.parser && self[name] && self[name].setEncoding(options.encoding || 'utf8');
});
// parse incoming data on stdout
if (this.parser && this.stdout) {
this.stdout.on('data', this.receive.bind(this));
}
// listen to stderr and emit errors for incoming data
if (this.stderr) {
this.stderr.on('data', function (data) {
errorData += '' + data;
self.receiveStderr(data);
});
this.stderr.on('end', function () {
self.stderrHasEnded = true;
terminateIfNeeded();
});
}
else {
self.stderrHasEnded = true;
}
if (this.stdout) {
this.stdout.on('end', function () {
self.stdoutHasEnded = true;
terminateIfNeeded();
});
}
else {
self.stdoutHasEnded = true;
}
this.childProcess.on('exit', function (code, signal) {
self.exitCode = code;
self.exitSignal = signal;
terminateIfNeeded();
});
function terminateIfNeeded() {
if (!self.stderrHasEnded || !self.stdoutHasEnded || (self.exitCode == null && self.exitSignal == null))
return;
let err;
if (self.exitCode && self.exitCode !== 0) {
if (errorData) {
err = self.parseError(errorData);
}
else {
err = new PythonShellError('process exited with code ' + self.exitCode);
}
err = extend(err, {
executable: pythonPath,
options: pythonOptions.length ? pythonOptions : null,
script: self.scriptPath,
args: scriptArgs.length ? scriptArgs : null,
exitCode: self.exitCode
});
// do not emit error if only a callback is used
if (self.listeners('error').length || !self._endCallback) {
self.emit('error', err);
}
}
self.terminated = true;
self.emit('close');
self._endCallback && self._endCallback(err, self.exitCode, self.exitSignal);
}
;
}
/**
* checks syntax without executing code
* @param {string} code
* @returns {Promise} rejects w/ stderr if syntax failure
*/
static checkSyntax(code) {
return __awaiter(this, void 0, void 0, function* () {
const randomInt = getRandomInt();
const filePath = os_1.tmpdir() + path_1.sep + `pythonShellSyntaxCheck${randomInt}.py`;
// todo: replace this with util.promisify (once we no longer support node v7)
return new Promise((resolve, reject) => {
fs_1.writeFile(filePath, code, (err) => {
if (err)
reject(err);
resolve(this.checkSyntaxFile(filePath));
});
});
});
}
static getPythonPath() {
return this.defaultOptions.pythonPath ? this.defaultOptions.pythonPath : this.defaultPythonPath;
}
/**
* checks syntax without executing code
* @param {string} filePath
* @returns {Promise} rejects w/ stderr if syntax failure
*/
static checkSyntaxFile(filePath) {
return __awaiter(this, void 0, void 0, function* () {
const pythonPath = this.getPythonPath();
const compileCommand = `${pythonPath} -m py_compile ${filePath}`;
return new Promise((resolve, reject) => {
child_process_1.exec(compileCommand, (error, stdout, stderr) => {
if (error == null)
resolve();
else
reject(stderr);
});
});
});
}
/**
* 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} callback The callback function to invoke with the script results
* @return {PythonShell} The PythonShell instance
*/
static run(scriptPath, options, callback) {
let pyshell = new PythonShell(scriptPath, options);
let output = [];
return pyshell.on('message', function (message) {
output.push(message);
}).end(function (err) {
if (err)
return callback(err);
return callback(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
*/
static runString(code, options, callback) {
// put code in temp file
const randomInt = getRandomInt();
const filePath = os_1.tmpdir + path_1.sep + `pythonShellFile${randomInt}.py`;
fs_1.writeFileSync(filePath, code);
return PythonShell.run(filePath, options, callback);
}
;
static getVersion(pythonPath) {
if (!pythonPath)
pythonPath = this.getPythonPath();
const execPromise = util_1.promisify(child_process_1.exec);
return execPromise(pythonPath + " --version");
}
static getVersionSync(pythonPath) {
if (!pythonPath)
pythonPath = this.getPythonPath();
return child_process_1.execSync(pythonPath + " --version").toString();
}
/**
* Parses an error thrown from the Python process through stderr
* @param {string|Buffer} data The stderr contents to parse
* @return {Error} The parsed error with extended stack trace when traceback is available
*/
parseError(data) {
let text = '' + data;
let error;
if (/^Traceback/.test(text)) {
// traceback data is available
let lines = ('' + data).trim().split(new RegExp(os_1.EOL, 'g'));
let exception = lines.pop();
error = new PythonShellError(exception);
error.traceback = data;
// extend stack trace
error.stack += os_1.EOL + ' ----- Python Traceback -----' + os_1.EOL + ' ';
error.stack += lines.slice(1).join(os_1.EOL + ' ');
}
else {
// otherwise, create a simpler error with stderr contents
error = new PythonShellError(text);
}
return error;
}
;
/**
* Sends a message to the Python shell through stdin
* Override this method to format data to be sent to the Python process
* @param {string|Object} data The message to send
* @returns {PythonShell} The same instance for chaining calls
*/
send(message) {
if (!this.stdin)
throw new Error("stdin not open for writting");
let data = this.formatter ? this.formatter(message) : message;
if (this.mode !== 'binary')
data += os_1.EOL;
this.stdin.write(data);
return this;
}
;
/**
* Parses data received from the Python shell stdout stream and emits "message" events
* This method is not used in binary mode
* Override this method to parse incoming data from the Python process into messages
* @param {string|Buffer} data The data to parse into messages
*/
receive(data) {
return this.receiveInternal(data, 'message');
}
;
/**
* Parses data received from the Python shell stderr stream and emits "stderr" events
* This method is not used in binary mode
* Override this method to parse incoming logs from the Python process into messages
* @param {string|Buffer} data The data to parse into messages
*/
receiveStderr(data) {
return this.receiveInternal(data, 'stderr');
}
;
receiveInternal(data, emitType) {
let self = this;
let parts = ('' + data).split(new RegExp(os_1.EOL, 'g'));
if (parts.length === 1) {
// an incomplete record, keep buffering
this._remaining = (this._remaining || '') + parts[0];
return this;
}
let lastLine = parts.pop();
// fix the first line with the remaining from the previous iteration of 'receive'
parts[0] = (this._remaining || '') + parts[0];
// keep the remaining for the next iteration of 'receive'
this._remaining = lastLine;
parts.forEach(function (part) {
if (emitType == 'message')
self.emit(emitType, self.parser(part));
else if (emitType == 'stderr')
self.emit(emitType, self.stderrParser(part));
});
return this;
}
/**
* Closes the stdin stream, which should cause the process to finish its work and close
* @returns {PythonShell} The same instance for chaining calls
*/
end(callback) {
if (this.childProcess.stdin) {
this.childProcess.stdin.end();
}
this._endCallback = callback;
return this;
}
;
/**
* Closes the stdin stream, which should cause the process to finish its work and close
* @returns {PythonShell} The same instance for chaining calls
*/
terminate(signal) {
this.childProcess.kill(signal);
this.terminated = true;
return this;
}
;
}
// starting 2020 python2 is deprecated so we choose 3 as default
PythonShell.defaultPythonPath = process.platform != "win32" ? "python3" : "py";
PythonShell.defaultOptions = {}; //allow global overrides for options
// built-in formatters
PythonShell.format = {
text: function toText(data) {
if (!data)
return '';
else if (typeof data !== 'string')
return data.toString();
return data;
},
json: function toJson(data) {
return JSON.stringify(data);
}
};
//built-in parsers
PythonShell.parse = {
text: function asText(data) {
return data;
},
json: function asJson(data) {
return JSON.parse(data);
}
};
exports.PythonShell = PythonShell;
;
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+71
View File
@@ -0,0 +1,71 @@
{
"_from": "python-shell@^1.0.7",
"_id": "python-shell@1.0.8",
"_inBundle": false,
"_integrity": "sha512-jMKagerg3alm6j+Prq5t/M3dTgEppy5vC6ns+LqAjfuHiT8olfK3PMokpqpeEcWEqvDnUcAOhp6SQzaLBtTzRw==",
"_location": "/python-shell",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "python-shell@^1.0.7",
"name": "python-shell",
"escapedName": "python-shell",
"rawSpec": "^1.0.7",
"saveSpec": null,
"fetchSpec": "^1.0.7"
},
"_requiredBy": [
"#DEV:/"
],
"_resolved": "https://registry.npmjs.org/python-shell/-/python-shell-1.0.8.tgz",
"_shasum": "067bc93d790913efaa4b2a3c9d0e85e02adab510",
"_spec": "python-shell@^1.0.7",
"_where": "/home/pi/Desktop/Git/smartMirror/modules/MMM-flick-gestures",
"author": {
"name": "Nicolas Mercier",
"email": "nicolas@extrabacon.net"
},
"bugs": {
"url": "http://github.com/extrabacon/python-shell/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Run Python scripts from Node.js with simple (but efficient) inter-process communication through stdio",
"devDependencies": {
"@types/mocha": "^5.2.5",
"@types/node": "^9.3.0",
"mocha": "^5.2.0",
"mocha-appveyor-reporter": "^0.4.0",
"should": "^13.2.1",
"ts-node": "^7.0.1",
"typescript": "^3.0.1"
},
"engines": {
"node": ">=0.10"
},
"files": [
"*.d.ts",
"*.js",
"*.js.map",
"CHANGELOG.md",
"README.md"
],
"homepage": "http://github.com/extrabacon/python-shell",
"keywords": [
"python"
],
"license": "MIT",
"name": "python-shell",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/extrabacon/python-shell.git"
},
"scripts": {
"appveyorTest": "tsc -p ./ && nyc mocha --reporter mocha-appveyor-reporter test/*.js",
"compile": "tsc -watch -p ./",
"test": "tsc -p ./ && mocha"
},
"version": "1.0.8"
}