-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpyodide.worker.js
More file actions
242 lines (221 loc) · 6.39 KB
/
pyodide.worker.js
File metadata and controls
242 lines (221 loc) · 6.39 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Pyodide web worker
let pyodide;
let pyodideOutput = [];
const PYODIDE_CDN = `https://cdn.jsdelivr.net/pyodide/v0.28.1/full/`;
// Helper function to read all files from the Pyodide file system
function readAllFiles() {
const dirFiles = pyodide.FS.readdir(HOME);
const updatedFiles = [];
for (const filename of dirFiles) {
if (filename === "." || filename === "..") continue;
const filepath = HOME + filename;
const stat = pyodide.FS.stat(filepath);
if (pyodide.FS.isFile(stat.mode)) {
const content = pyodide.FS.readFile(filepath, { encoding: "utf8" });
updatedFiles.push([filename, content]);
}
}
return updatedFiles;
}
async function init(id, payload) {
const { interruptBuffer } = payload;
if (!pyodide) {
importScripts(`${PYODIDE_CDN}pyodide.js`);
pyodide = await loadPyodide({
indexURL: PYODIDE_CDN,
});
pyodide.setStdout({
batched: (str) => {
pyodideOutput.push({ type: "stdout", message: str });
},
});
pyodide.setStderr({
batched: (str) => {
pyodideOutput.push({ type: "stderr", message: str });
},
});
pyodide.setInterruptBuffer(interruptBuffer);
}
self.postMessage({ id, payload: { success: true } });
}
async function runPython(id, payload) {
const { code } = payload;
if (!pyodide) {
self.postMessage({ id, error: "Pyodide not initialized" });
return;
}
try {
const result = await pyodide.runPythonAsync(code);
if (result !== undefined) {
pyodideOutput.push({
type: "return",
message: String(result),
});
} else {
// 標準出力/エラーがない場合
}
} catch (e) {
console.log(e);
if (e instanceof Error) {
// エラーがPyodideのTracebackの場合、2行目から<exec>が出てくるまでを隠す
if (e.name === "PythonError" && e.message.startsWith("Traceback")) {
const lines = e.message.split("\n");
const execLineIndex = lines.findIndex((line) =>
line.includes("<exec>")
);
pyodideOutput.push({
type: "error",
message: lines
.slice(0, 1)
.concat(lines.slice(execLineIndex))
.join("\n")
.trim(),
});
} else {
pyodideOutput.push({
type: "error",
message: `予期せぬエラー: ${e.message.trim()}`,
});
}
} else {
pyodideOutput.push({
type: "error",
message: `予期せぬエラー: ${String(e).trim()}`,
});
}
}
const updatedFiles = readAllFiles();
const output = [...pyodideOutput];
pyodideOutput = []; // 出力をクリア
self.postMessage({
id,
payload: { output, updatedFiles },
});
}
async function runFile(id, payload) {
const { name, files } = payload;
if (!pyodide) {
self.postMessage({ id, error: "Pyodide not initialized" });
return;
}
try {
// Use Pyodide FS API to write files to the file system
for (const filename of Object.keys(files)) {
if (files[filename]) {
pyodide.FS.writeFile(HOME + filename, files[filename], {
encoding: "utf8",
});
}
}
const pyExecFile = pyodide.runPython(EXECFILE_CODE); /* as PyCallable*/
pyExecFile(HOME + name);
} catch (e) {
console.log(e);
if (e instanceof Error) {
// エラーがPyodideのTracebackの場合、2行目から<exec>が出てくるまでを隠す
// <exec> 自身も隠す
if (e.name === "PythonError" && e.message.startsWith("Traceback")) {
const lines = e.message.split("\n");
const execLineIndex = lines.findLastIndex((line) =>
line.includes("<exec>")
);
pyodideOutput.push({
type: "error",
message: lines
.slice(0, 1)
.concat(lines.slice(execLineIndex + 1))
.join("\n")
.trim(),
});
} else {
pyodideOutput.push({
type: "error",
message: `予期せぬエラー: ${e.message.trim()}`,
});
}
} else {
pyodideOutput.push({
type: "error",
message: `予期せぬエラー: ${String(e).trim()}`,
});
}
}
const updatedFiles = readAllFiles();
const output = [...pyodideOutput];
pyodideOutput = []; // 出力をクリア
self.postMessage({
id,
payload: { output, updatedFiles },
});
}
async function checkSyntax(id, payload) {
const { code } = payload;
if (!pyodide) {
self.postMessage({
id,
payload: { status: "invalid" },
});
return;
}
try {
// Pythonのコードを実行して結果を受け取る
const status = pyodide.runPython(CHECK_SYNTAX_CODE)(code);
self.postMessage({ id, payload: { status } });
} catch (e) {
console.error("Syntax check error:", e);
self.postMessage({
id,
payload: { status: "invalid" },
});
}
}
self.onmessage = async (event) => {
const { id, type, payload } = event.data;
switch (type) {
case "init":
await init(id, payload);
return;
case "runPython":
await runPython(id, payload);
return;
case "runFile":
await runFile(id, payload);
return;
case "checkSyntax":
await checkSyntax(id, payload);
return;
default:
console.error(`Unknown message type: ${type}`);
return;
}
};
// Python側で実行する構文チェックのコード
// codeop.compile_commandは、コードが不完全な場合はNoneを返します。
const CHECK_SYNTAX_CODE = `
def __check_syntax(code):
import codeop
compiler = codeop.compile_command
try:
# compile_commandは、コードが完結していればコンパイルオブジェクトを、
# 不完全(まだ続きがある)であればNoneを返す
if compiler(code) is not None:
return "complete"
else:
return "incomplete"
except (SyntaxError, ValueError, OverflowError):
# 明らかな構文エラーの場合
return "invalid"
__check_syntax
`;
const HOME = `/home/pyodide/`;
// https://stackoverflow.com/questions/436198/what-alternative-is-there-to-execfile-in-python-3-how-to-include-a-python-fil
const EXECFILE_CODE = `
def __execfile(filepath):
with open(filepath, 'rb') as file:
exec_globals = {
"__file__": filepath,
"__name__": "__main__",
}
exec(compile(file.read(), filepath, 'exec'), exec_globals)
__execfile
`;