UNPKG

python-js-executor

Version:

Execute Python code and files from JavaScript with full import support

77 lines (66 loc) 2.08 kB
const { PythonShell } = require('python-shell'); const path = require('path'); const fs = require('fs'); const os = require('os'); class PythonRunner { constructor() { this.pythonPath = 'python3'; } /** * Run Python code from a file * @param {string} pythonFile - Path to the Python file * @param {Array} args - Arguments to pass to the Python script * @returns {Promise} - Resolves with the Python script output */ runFile(pythonFile, args = []) { return new Promise((resolve, reject) => { const options = { mode: 'text', pythonPath: this.pythonPath, pythonOptions: ['-u'], // unbuffered output scriptPath: path.dirname(pythonFile), args: args }; PythonShell.run(path.basename(pythonFile), options) .then(results => resolve(results)) .catch(err => reject(err)); }); } /** * Run Python code directly from a string * @param {string} code - Python code to execute * @param {Array} args - Arguments to pass to the Python code * @returns {Promise} - Resolves with the Python code output */ runCode(code, args = []) { return new Promise((resolve, reject) => { // Create a temporary file for the Python code const tempFile = path.join(os.tmpdir(), `python_${Date.now()}.py`); fs.writeFileSync(tempFile, code); const options = { mode: 'text', pythonPath: this.pythonPath, pythonOptions: ['-u'], args: args }; // Create PythonShell instance with the temporary file const pyshell = new PythonShell(tempFile, options); let output = []; pyshell.on('message', (message) => { output.push(message); }); pyshell.on('error', (err) => { // Clean up the temporary file fs.unlinkSync(tempFile); reject(err); }); pyshell.on('close', () => { // Clean up the temporary file fs.unlinkSync(tempFile); resolve(output); }); pyshell.end(); }); } } module.exports = PythonRunner;