Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # [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)
  2. <!-- chage above url accroding to repo -->
  3. A simple way to run Python scripts from Node.js with basic but efficient inter-process communication and better error handling.
  4. ## Features
  5. + Reliably spawn Python scripts in a child process
  6. + Built-in text, JSON and binary modes
  7. + Custom parsers and formatters
  8. + Simple and efficient data transfers through stdin and stdout streams
  9. + Extended stack traces when an error is thrown
  10. ## Installation
  11. ```bash
  12. npm install python-shell
  13. ```
  14. To run the tests:
  15. ```bash
  16. npm test
  17. ```
  18. ## Documentation
  19. ### Running python code:
  20. ```typescript
  21. import {PythonShell} from 'python-shell';
  22. PythonShell.runString('x=1+1;print(x)', null, function (err) {
  23. if (err) throw err;
  24. console.log('finished');
  25. });
  26. ```
  27. If the script exits with a non-zero code, an error will be thrown.
  28. 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).
  29. Or you can use require like so:
  30. ```javascript
  31. let {PythonShell} = require('python-shell')
  32. ```
  33. ### Running a Python script:
  34. ```typescript
  35. import {PythonShell} from 'python-shell';
  36. PythonShell.run('my_script.py', null, function (err) {
  37. if (err) throw err;
  38. console.log('finished');
  39. });
  40. ```
  41. If the script exits with a non-zero code, an error will be thrown.
  42. ### Running a Python script with arguments and options:
  43. ```typescript
  44. import {PythonShell} from 'python-shell';
  45. let options = {
  46. mode: 'text',
  47. pythonPath: 'path/to/python',
  48. pythonOptions: ['-u'], // get print results in real-time
  49. scriptPath: 'path/to/my/scripts',
  50. args: ['value1', 'value2', 'value3']
  51. };
  52. PythonShell.run('my_script.py', options, function (err, results) {
  53. if (err) throw err;
  54. // results is an array consisting of messages collected during execution
  55. console.log('results: %j', results);
  56. });
  57. ```
  58. ### Exchanging data between Node and Python:
  59. ```typescript
  60. import {PythonShell} from 'python-shell';
  61. let pyshell = new PythonShell('my_script.py');
  62. // sends a message to the Python script via stdin
  63. pyshell.send('hello');
  64. pyshell.on('message', function (message) {
  65. // received a message sent from the Python script (a simple "print" statement)
  66. console.log(message);
  67. });
  68. // end the input stream and allow the process to exit
  69. pyshell.end(function (err,code,signal) {
  70. if (err) throw err;
  71. console.log('The exit code was: ' + code);
  72. console.log('The exit signal was: ' + signal);
  73. console.log('finished');
  74. console.log('finished');
  75. });
  76. ```
  77. Use `.send(message)` to send a message to the Python script. Attach the `message` event to listen to messages emitted from the Python script.
  78. Use `options.mode` to quickly setup how data is sent and received between your Node and Python applications.
  79. * use `text` mode for exchanging lines of text
  80. * use `json` mode for exchanging JSON fragments
  81. * use `binary` mode for anything else (data is sent and received as-is)
  82. For more details and examples including Python source code, take a look at the tests.
  83. ### Error Handling and extended stack traces
  84. 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.
  85. Sample error with traceback (from test/python/error.py):
  86. ```
  87. Traceback (most recent call last):
  88. File "test/python/error.py", line 6, in <module>
  89. divide_by_zero()
  90. File "test/python/error.py", line 4, in divide_by_zero
  91. print 1/0
  92. ZeroDivisionError: integer division or modulo by zero
  93. ```
  94. would result into the following error:
  95. ```typescript
  96. { [Error: ZeroDivisionError: integer division or modulo by zero]
  97. 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',
  98. executable: 'python',
  99. options: null,
  100. script: 'test/python/error.py',
  101. args: null,
  102. exitCode: 1 }
  103. ```
  104. and `err.stack` would look like this:
  105. ```
  106. Error: ZeroDivisionError: integer division or modulo by zero
  107. at PythonShell.parseError (python-shell/index.js:131:17)
  108. at ChildProcess.<anonymous> (python-shell/index.js:67:28)
  109. at ChildProcess.EventEmitter.emit (events.js:98:17)
  110. at Process.ChildProcess._handle.onexit (child_process.js:797:12)
  111. ----- Python Traceback -----
  112. File "test/python/error.py", line 6, in <module>
  113. divide_by_zero()
  114. File "test/python/error.py", line 4, in divide_by_zero
  115. print 1/0
  116. ```
  117. ## API Reference
  118. #### `PythonShell(script, options)` constructor
  119. Creates an instance of `PythonShell` and starts the Python process
  120. * `script`: the path of the script to execute
  121. * `options`: the execution options, consisting of:
  122. * `mode`: Configures how data is exchanged when data flows through stdin and stdout. The possible values are:
  123. * `text`: each line of data (ending with "\n") is emitted as a message (default)
  124. * `json`: each line of data (ending with "\n") is parsed as JSON and emitted as a message
  125. * `binary`: data is streamed as-is through `stdout` and `stdin`
  126. * `formatter`: each message to send is transformed using this method, then appended with "\n"
  127. * `parser`: each line of data (ending with "\n") is parsed with this function and its result is emitted as a message
  128. * `stderrParser`: each line of logs (ending with "\n") is parsed with this function and its result is emitted as a message
  129. * `encoding`: the text encoding to apply on the child process streams (default: "utf8")
  130. * `pythonPath`: The path where to locate the "python" executable. Default: "python"
  131. * `pythonOptions`: Array of option switches to pass to "python"
  132. * `scriptPath`: The default path where to look for scripts. Default is the current working directory.
  133. * `args`: Array of arguments to pass to the script
  134. Other options are forwarded to `child_process.spawn`.
  135. PythonShell instances have the following properties:
  136. * `script`: the path of the script to execute
  137. * `command`: the full command arguments passed to the Python executable
  138. * `stdin`: the Python stdin stream, used to send data to the child process
  139. * `stdout`: the Python stdout stream, used for receiving data from the child process
  140. * `stderr`: the Python stderr stream, used for communicating logs & errors
  141. * `childProcess`: the process instance created via `child_process.spawn`
  142. * `terminated`: boolean indicating whether the process has exited
  143. * `exitCode`: the process exit code, available after the process has ended
  144. Example:
  145. ```typescript
  146. // create a new instance
  147. let shell = new PythonShell('script.py', options);
  148. ```
  149. #### `#defaultOptions`
  150. Configures default options for all new instances of PythonShell.
  151. Example:
  152. ```typescript
  153. // setup a default "scriptPath"
  154. PythonShell.defaultOptions = { scriptPath: '../scripts' };
  155. ```
  156. #### `#run(script, options, callback)`
  157. 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.
  158. This method is also returning the `PythonShell` instance.
  159. Example:
  160. ```typescript
  161. // run a simple script
  162. PythonShell.run('script.py', null, function (err, results) {
  163. // script finished
  164. });
  165. ```
  166. #### `#runString(code, options, callback)`
  167. 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.
  168. This method is also returning the `PythonShell` instance.
  169. Example:
  170. ```typescript
  171. // run a simple script
  172. PythonShell.runString('x=1;print(x)', null, function (err, results) {
  173. // script finished
  174. });
  175. ```
  176. #### `#checkSyntax(code:string)`
  177. Checks the syntax of the code and returns a promise.
  178. Promise is rejected if there is a syntax error.
  179. #### `#checkSyntaxFile(filePath:string)`
  180. Checks the syntax of the file and returns a promise.
  181. Promise is rejected if there is a syntax error.
  182. #### `#getVersion(pythonPath?:string)`
  183. Returns the python version. Optional pythonPath param to get the version
  184. of a specific python interpreter.
  185. #### `#getVersionSync(pythonPath?:string)`
  186. Returns the python version. Optional pythonPath param to get the version
  187. of a specific python interpreter.
  188. #### `.send(message)`
  189. 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.
  190. Example:
  191. ```typescript
  192. // send a message in text mode
  193. let shell = new PythonShell('script.py', { mode: 'text '});
  194. shell.send('hello world!');
  195. // send a message in JSON mode
  196. let shell = new PythonShell('script.py', { mode: 'json '});
  197. shell.send({ command: "do_stuff", args: [1, 2, 3] });
  198. ```
  199. #### `.receive(data)`
  200. 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.
  201. #### `.receiveStderr(data)`
  202. 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.
  203. #### `.end(callback)`
  204. Closes the stdin stream, allowing the Python script to finish and exit. The optional callback is invoked when the process is terminated.
  205. #### `.terminate(signal)`
  206. 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.
  207. #### event: `message`
  208. 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.
  209. Example:
  210. ```typescript
  211. // receive a message in text mode
  212. let shell = new PythonShell('script.py', { mode: 'text '});
  213. shell.on('message', function (message) {
  214. // handle message (a line of text from stdout)
  215. });
  216. // receive a message in JSON mode
  217. let 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. #### event: `stderr`
  223. 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.
  224. Example:
  225. ```typescript
  226. // receive a message in text mode
  227. let shell = new PythonShell('script.py', { mode: 'text '});
  228. shell.on('stderr', function (stderr) {
  229. // handle stderr (a line of text from stderr)
  230. });
  231. ```
  232. #### event: `close`
  233. Fires when the process has been terminated, with an error or not.
  234. #### event: `error`
  235. Fires when the process terminates with a non-zero exit code.
  236. ## Used By:
  237. 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!
  238. ## License
  239. The MIT License (MIT)
  240. Copyright (c) 2014 Nicolas Mercier
  241. Permission is hereby granted, free of charge, to any person obtaining a copy
  242. of this software and associated documentation files (the "Software"), to deal
  243. in the Software without restriction, including without limitation the rights
  244. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  245. copies of the Software, and to permit persons to whom the Software is
  246. furnished to do so, subject to the following conditions:
  247. The above copyright notice and this permission notice shall be included in
  248. all copies or substantial portions of the Software.
  249. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  250. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  251. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  252. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  253. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  254. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  255. THE SOFTWARE.