-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-simple.html
More file actions
149 lines (124 loc) · 5.06 KB
/
python-simple.html
File metadata and controls
149 lines (124 loc) · 5.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python编程环境 - 基础版</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/python/python.min.js"></script>
<script src="https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js"></script>
</head>
<body class="bg-dark text-light">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<h3>Python代码编辑器</h3>
<div id="loadingStatus" class="alert alert-info">正在加载Python环境...</div>
<textarea id="code" class="form-control"># Python基础编程环境
print("Hello, Python!")
# 示例:计算平均分
scores = [85, 92, 78, 96]
average = sum(scores) / len(scores)
print(f"平均分: {average:.1f}")
</textarea>
<div class="mt-3">
<button id="runBtn" class="btn btn-primary" onclick="runCode()" disabled>运行代码</button>
<button class="btn btn-secondary" onclick="clearCode()">清空</button>
</div>
</div>
<div class="col-md-6">
<h3>运行结果</h3>
<pre id="output" class="bg-secondary p-3 text-light" style="min-height: 300px;">等待代码运行...</pre>
</div>
</div>
</div>
<script>
let pyodide;
let editor;
// 初始化CodeMirror
const codeTextarea = document.getElementById('code');
editor = CodeMirror.fromTextArea(codeTextarea, {
mode: 'python',
theme: 'default',
lineNumbers: true,
indentUnit: 4
});
// 加载Pyodide
async function main() {
try {
document.getElementById('loadingStatus').textContent = '正在加载Python环境...';
pyodide = await loadPyodide({
indexURL: "https://cdn.jsdelivr.net/pyodide/v0.24.1/full/"
});
// 基础配置
pyodide.runPython(`
import sys
from io import StringIO
class OutputCapture:
def __init__(self):
self.outputs = []
def write(self, text):
self.outputs.append(text)
def flush(self):
pass
def get_output(self):
result = ''.join(self.outputs)
self.outputs = []
return result
output_capture = OutputCapture()
def input(prompt=""):
print(f"{prompt}[模拟输入: 用户]")
return "用户"
print("🎉 Python环境已就绪!")
`);
document.getElementById('loadingStatus').innerHTML =
'<div class="alert alert-success">✅ Python环境已就绪,可以开始编程!</div>';
document.getElementById('runBtn').disabled = false;
} catch (error) {
console.error('Pyodide加载失败:', error);
document.getElementById('loadingStatus').innerHTML =
'<div class="alert alert-danger">❌ Python环境加载失败,请刷新页面重试</div>';
}
}
// 运行代码
async function runCode() {
if (!pyodide) {
alert('Python环境未准备就绪');
return;
}
const code = editor.getValue();
const outputDiv = document.getElementById('output');
try {
// 重定向输出
pyodide.runPython(`
sys.stdout = output_capture
sys.stderr = output_capture
`);
// 运行用户代码
pyodide.runPython(code);
// 获取输出
const output = pyodide.runPython('output_capture.get_output()');
// 恢复标准输出
pyodide.runPython(`
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
`);
// 显示结果
const timestamp = new Date().toLocaleTimeString();
outputDiv.textContent = `[${timestamp}] 运行完成:\n${output || '(无输出)'}`;
} catch (error) {
const timestamp = new Date().toLocaleTimeString();
outputDiv.textContent = `[${timestamp}] 运行错误:\n${error.message}`;
outputDiv.style.color = '#ff6b6b';
}
}
function clearCode() {
editor.setValue('# 在这里编写你的Python代码\nprint("Hello, World!")');
}
// 启动应用
main();
</script>
</body>
</html>