@@ -3,7 +3,7 @@ import { ChildProcess,spawn, SpawnOptions, exec } from 'child_process';
33import { EOL as newline , tmpdir } from 'os' ;
44import { join , sep } from 'path'
55import { Readable , Writable } from 'stream'
6- import { writeFile } from 'fs' ;
6+ import { writeFile , writeFileSync } from 'fs' ;
77
88function toArray < T > ( source ?:T | T [ ] ) :T [ ] {
99 if ( typeof source === 'undefined' || source === null ) {
@@ -198,7 +198,7 @@ export class PythonShell extends EventEmitter{
198198 * @returns {Promise } rejects w/ stderr if syntax failure
199199 */
200200 static async checkSyntax ( code :string ) {
201- let randomInt = Math . floor ( Math . random ( ) * 10000000000 ) ;
201+ let randomInt = PythonShell . getRandomInt ( ) ;
202202 let filePath = tmpdir + sep + `pythonShellSyntaxCheck${ randomInt } .py`
203203
204204 // todo: replace this with util.promisify (once we no longer support node v7)
@@ -246,6 +246,23 @@ export class PythonShell extends EventEmitter{
246246 } ) ;
247247 } ;
248248
249+ /**
250+ * Runs the inputted string of python code and returns collected messages. DO NOT ALLOW UNTRUSTED USER INPUT HERE!
251+ * @param {string } code The python code to execute
252+ * @param {Options } options The execution options
253+ * @param {Function } callback The callback function to invoke with the script results
254+ * @return {PythonShell } The PythonShell instance
255+ */
256+ static runString ( code :string , options ?:Options , callback ?:( err :PythonShellError , output ?:any [ ] ) => any ) {
257+
258+ // put code in temp file
259+ let randomInt = PythonShell . getRandomInt ( ) ;
260+ let filePath = tmpdir + sep + `pythonShellFile${ randomInt } .py`
261+ writeFileSync ( filePath , code ) ;
262+
263+ return PythonShell . run ( filePath , options , callback ) ;
264+ } ;
265+
249266 /**
250267 * Parses an error thrown from the Python process through stderr
251268 * @param {string|Buffer } data The stderr contents to parse
@@ -272,6 +289,13 @@ export class PythonShell extends EventEmitter{
272289 return error ;
273290 } ;
274291
292+ /**
293+ * gets a random int from 0-10000000000
294+ */
295+ private static getRandomInt ( ) {
296+ return Math . floor ( Math . random ( ) * 10000000000 ) ;
297+ }
298+
275299 /**
276300 * Sends a message to the Python shell through stdin
277301 * Override this method to format data to be sent to the Python process
0 commit comments