如何从Node.js运行Python脚本?附完整示例代码
How to Run a Python Script from Node.js with Data Interaction
Let’s get your setup working end-to-end. I’ll complete both your Node.js and Python scripts, break down how the data flow works, and cover common pitfalls to avoid.
Step 1: Finalize the Node.js Script (start.js)
Your existing script is almost there—let’s add error handling to catch issues and make the code more robust:
// start.js const spawn = require('child_process').spawn; const py = spawn('python', ['compute_input.py']); // Use 'python3' if needed on your system const data = [1,2,3,4,5,6,7,8,9]; let dataString = ''; // Capture output from Python's stdout py.stdout.on('data', (data) => { dataString += data.toString(); }); // Process the final output once Python finishes py.stdout.on('end', () => { try { const result = JSON.parse(dataString); console.log('Sum of numbers:', result.sum); } catch (err) { console.error('Failed to parse Python output:', err); console.error('Raw output received:', dataString); } }); // Catch any errors from the Python process py.stderr.on('data', (data) => { console.error('Python runtime error:', data.toString()); }); // Send data to Python via stdin py.stdin.write(JSON.stringify(data)); py.stdin.end(); // Signal no more input will be sent
Key Node.js Details:
- Added
stderrhandling to catch Python errors (like missing modules or syntax issues). - Wrapped JSON parsing in a try/catch to handle cases where Python’s output isn’t valid JSON.
- Used modern
const/letinstead ofvarfor cleaner code.
Step 2: Complete the Python Script (compute_input.py)
Your partial script needs to properly read input from stdin, process it, and send results back. Here’s the full working version:
# compute_input.py import sys import json import numpy as np def read_in(): # Read all input from stdin (Node.js sends JSON as a single string) input_data = sys.stdin.read() # Parse JSON into a Python list return json.loads(input_data) def main(): # Get data from Node.js numbers = read_in() # Convert to numpy array (optional, but matches your import) np_numbers = np.array(numbers) # Calculate the sum total_sum = np.sum(np_numbers) # Send result back as JSON (easy to parse in Node.js) result = {"sum": int(total_sum)} print(json.dumps(result)) if __name__ == "__main__": main()
Key Python Details:
sys.stdin.read()reads all input at once (ideal here since Node.js sends the entire JSON payload in one write).- We use
print(json.dumps(result))to send the result back as a JSON string—this ensures Node.js can parse it easily. - The
main()function andif __name__ == "__main__":check ensures the code only runs when the script is executed directly.
How the Data Flow Works
- Node.js initiates the process: Uses
spawnto start the Python script, then writes the JSON-serialized number list to Python’sstdin. - Python processes the data: Reads the JSON from
stdin, parses it into a list, computes the sum (using numpy), then serializes the result back to JSON and prints it tostdout. - Node.js receives the result: Listens to Python’s
stdout, collects the output, parses the JSON, and logs the final sum.
Troubleshooting Tips
- Python not found: If you get
spawn python ENOENT, replacepythonwithpython3in the Node.js script (depends on your system’s Python installation). - Missing numpy: Install it with
pip install numpyif Python throws an import error. - No output received: Ensure you call
py.stdin.end()in Node.js—this tells Python there’s no more input coming, so it can finish processing. - Invalid JSON errors: Avoid printing debug messages in Python (they’ll break the JSON output sent to Node.js).
内容的提问来源于stack exchange,提问作者rakamakafo
相关产品推荐
相关产品推荐

