The error occurs because Brython isn't loading properly. Here's the corrected version that properly loads and initializes Brython:
<!DOCTYPE html>
<html>
<head>
<title>Brython Python Runner</title>
<script src="https://unpkg.com/brython@3/www/src/brython.js"></script>
<script src="https://unpkg.com/brython@3/www/src/brython_stdlib.js"></script>
</head>
<body>
<h2>Python Code Runner (Brython)</h2>
<textarea id="code" style="width:100%; height:200px;">
# Example Python code
print("Hello from Brython!")
for i in range(5):
print(f"Count: {i}")
# You can use most Python features
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers]
print("Squared numbers:", squared)
</textarea>
<br>
<button onclick="runPython()">Run Python Code</button>
<button onclick="clearOutput()">Clear Output</button>
<pre id="output" style="background-color: #f0f0f0; padding: 10px; margin-top: 10px;"></pre>
<script>
// Initialize Brython when page loads
window.addEventListener('load', function() {
if (typeof brython !== 'undefined') {
brython(1); // Initialize Brython with debug mode
console.log("Brython initialized successfully");
} else {
console.error("Brython failed to load");
document.getElementById('output').innerHTML = "Error: Brython failed to load. Check your internet connection.";
}
});
function runPython() {
const code = document.getElementById('code').value;
const output = document.getElementById('output');
// Clear previous output
output.innerHTML = '';
try {
// Create a script element with Python code
const scriptElement = document.createElement('script');
scriptElement.type = 'text/python';
scriptElement.textContent = `
import sys
from browser import document
# Redirect print output to our output div
class OutputCapture:
def __init__(self):
self.content = ""
def write(self, text):
self.content += str(text)
document["output"].text = self.content
def flush(self):
pass
# Replace stdout
output_capture = OutputCapture()
sys.stdout = output_capture
# Execute user code
try:
${code}
except Exception as e:
print(f"Error: {e}")
`;
// Remove any existing python scripts
const existingScripts = document.querySelectorAll('script[type="text/python"]');
existingScripts.forEach(script => script.remove());
// Add new script and run it
document.body.appendChild(scriptElement);
// Run Brython on the new script
if (typeof brython !== 'undefined') {
brython(1);
}
} catch (e) {
output.innerHTML = `Error: ${e.message}`;
}
}
function clearOutput() {
document.getElementById('output').innerHTML = '';
}
</script>
</body>
</html>
If Brython still doesn't work, here's an alternative using Pyodide (another Python-in-browser solution):
<!DOCTYPE html>
<html>
<head>
<title>Python Runner (Pyodide)</title>
<script src="https://unpkg.com/pyodide/pyodide.js"></script>
</head>
<body>
<h2>Python Code Runner (Pyodide)</h2>
<textarea id="code" style="width:100%; height:200px;">
# Example Python code
print("Hello from Pyodide!")
for i in range(5):
print(f"Count: {i}")
# Math operations
import math
print(f"Square root of 16: {math.sqrt(16)}")
# List operations
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers]
print("Squared numbers:", squared)
</textarea>
<br>
<button onclick="runPython()" id="runBtn">Run Python Code</button>
<button onclick="clearOutput()">Clear Output</button>
<pre id="output" style="background-color: #f0f0f0; padding: 10px; margin-top: 10px;">Loading Python environment...</pre>
<script>
let pyodide;
async function main() {
try {
pyodide = await loadPyodide();
document.getElementById('output').innerHTML = 'Python environment ready!';
document.getElementById('runBtn').disabled = false;
} catch (error) {
document.getElementById('output').innerHTML = `Error loading Pyodide: ${error}`;
}
}
async function runPython() {
if (!pyodide) {
document.getElementById('output').innerHTML = 'Python environment not ready yet!';
return;
}
const code = document.getElementById('code').value;
const output = document.getElementById('output');
try {
// Capture stdout
pyodide.runPython(`
import sys
from io import StringIO
# Redirect stdout to capture print statements
old_stdout = sys.stdout
sys.stdout = StringIO()
`);
// Run user code
pyodide.runPython(code);
// Get captured output
const result = pyodide.runPython(`
captured_output = sys.stdout.getvalue()
sys.stdout = old_stdout
captured_output
`);
output.innerHTML = result || 'Code executed successfully (no output)';
} catch (error) {
output.innerHTML = `Error: ${error}`;
}
}
function clearOutput() {
document.getElementById('output').innerHTML = '';
}
// Initialize when page loads
document.getElementById('runBtn').disabled = true;
main();
</script>
</body>
</html>
Troubleshooting Tips:
-
If both fail to load: Your network might be blocking CDN access. Try using a different network or ask IT about CDN restrictions.
-
Offline alternative: Save the libraries locally:
- Download
brython.js and brython_stdlib.js from unpkg.com while you have access
- Save them in the same folder as your HTML file
- Change the script src to local files:
<script src="brython.js"></script>
-
Simpler alternative: Use pure JavaScript with Python-like syntax:
<!DOCTYPE html>
<html>
<body>
<textarea id="code" style="width:100%; height:200px;">
// JavaScript with Python-like functions
function range(start, stop, step = 1) {
return Array.from({length: Math.ceil((stop - start) / step)}, (_, i) => start + i * step);
}
function print(...args) {
const output = document.getElementById('output');
output.innerHTML += args.join(' ') + '\n';
}
// Your code here
print("Hello World!");
for (let i of range(0, 5)) {
print("Count:", i);
}
</textarea>
<button onclick="runCode()">Run Code</button>
<pre id="output"></pre>
<script>
function runCode() {
document.getElementById('output').innerHTML = '';
eval(document.getElementById('code').value);
}
</script>
</body>
</html>
The Pyodide version tends to be more reliable and supports more Python features than Brython.