使用python-shell在Node.js中运行Python脚本时遇Error: init done问题求助
python-shell Initialization Error in Node.js Hey there, let's work through this error you're hitting when using python-shell in your Node.js project. That truncated error trace points to an issue during the initialization or output parsing phase of your Python script execution. Here are some practical fixes to try out:
Double-check your Python path configuration
A common culprit here is Node.js not being able to locate your Python executable. You can explicitly set the path when creating yourPythonShellinstance to eliminate this ambiguity:const { PythonShell } = require('python-shell'); const runOptions = { pythonPath: '/usr/bin/python3' // For Linux/macOS; use 'C:/Python311/python.exe' for Windows }; PythonShell.run('your_script.py', runOptions, (err, results) => { if (err) throw err; console.log('Script output:', results); });First, confirm your Python path works by running
python --versionorpython3 --versionin your terminal—use that exact path in your code.Test your Python script independently
Before running it through Node.js, execute your Python script directly in the terminal:python your_script.py. If the script has syntax errors, missing dependencies, or runtime issues,python-shellwill struggle to parse its output, leading to vague initialization errors. Fix any issues in the Python script first.Add detailed logging to capture full error context
The truncated error trace doesn't give you the whole picture. Add event listeners to capture the Python script's output and detailed errors:const pyshell = new PythonShell('your_script.py'); // Log regular output from Python pyshell.on('message', (message) => { console.log('Python says:', message); }); // Capture detailed error messages pyshell.on('error', (error) => { console.error('Full Python-shell error:', error); }); // Handle script termination pyshell.end((err, exitCode, signal) => { if (err) console.error('Termination error:', err); console.log('Script exited with code:', exitCode); });This will show you exactly what's going wrong, whether it's a script error, path issue, or output parsing problem.
Update or downgrade the
python-shellpackage
Outdated or incompatible package versions can cause initialization bugs. Try updating to the latest version first:npm update python-shellIf that doesn't help, downgrade to a known stable version (like 3.0.0, which is widely used):
npm install python-shell@3.0.0Check Node.js version compatibility
From theevents.jsreferences in your error trace, it looks like you're using an older Node.js version (likely v8.x or similar). Newerpython-shellversions may not play nicely with these older Node.js releases. Upgrade to an LTS version (like v16 or v18) and see if the error resolves.
内容的提问来源于stack exchange,提问作者Harkirat Singh

