import os import subprocess import tempfile from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/') def home(): return jsonify({ "status": "ok", "message": "Python interpreter backend is running. Send POST requests to /api/run-python" }) @app.route('/api/run-python', methods=['POST']) def run_python(): code = request.json.get('code', '') user_input = request.json.get('input', '') if not code: return jsonify({'error': 'No code provided.'}), 400 temp_file_path = None try: # Create a temporary file to write the Python code with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode='w', encoding='utf-8') as temp_file: temp_file.write(code) temp_file_path = temp_file.name # Run the Python script as a subprocess run_process = subprocess.run( ['python', temp_file_path], # The command to run input=user_input, capture_output=True, text=True, timeout=15 # Set a timeout for safety ) # Check if the process had errors if run_process.returncode != 0: return jsonify({'errors': run_process.stderr}) else: return jsonify({'output': run_process.stdout}) except subprocess.TimeoutExpired: return jsonify({'error': 'Code execution timed out (15 seconds limit).'}), 408 except Exception as e: return jsonify({'error': f"An unexpected error occurred: {str(e)}"}), 500 finally: # Clean up the temporary file, even if an error occurred if temp_file_path and os.path.exists(temp_file_path): os.remove(temp_file_path) if __name__ == '__main__': app.run(host="0.0.0.0", port=7860)