| 16 | } |
| 17 | |
| 18 | export async function execute(python_script: string) { |
| 19 | try { |
| 20 | await loadScript( |
| 21 | 'https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js' |
| 22 | ); |
| 23 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 24 | // @ts-ignore |
| 25 | const pyodide = await window.loadPyodide({ |
| 26 | indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.24.1/full/', |
| 27 | }); |
| 28 | |
| 29 | let stdout_content = ''; |
| 30 | |
| 31 | const stdoutHandler = { |
| 32 | batched: (str: string) => { |
| 33 | stdout_content += str + '\n'; |
| 34 | }, |
| 35 | }; |
| 36 | |
| 37 | pyodide.setStdout(stdoutHandler); |
| 38 | |
| 39 | await pyodide.loadPackagesFromImports(python_script); |
| 40 | |
| 41 | let result = await pyodide.runPython(python_script); |
| 42 | |
| 43 | // Check if result is a Pyodide proxy object |
| 44 | if (result && typeof result === 'object') { |
| 45 | // Check if the object is a list, array, map (dictionary), or set |
| 46 | if ( |
| 47 | 'length' in result || |
| 48 | result.constructor.name === 'PyProxyMap' || |
| 49 | result.constructor.name === 'PyProxySet' |
| 50 | ) { |
| 51 | // Try to convert the Python object to a JavaScript object |
| 52 | try { |
| 53 | result = result.toJs(); |
| 54 | } catch (error) { |
| 55 | console.error('Error converting Python object to JavaScript', error); |
| 56 | } |
| 57 | } else if ('toString' in result) { |
| 58 | // Fallback to using toString() for other types of objects |
| 59 | try { |
| 60 | result = result.toString(); |
| 61 | } catch (error) { |
| 62 | console.error('Error converting Python object to string', error); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Reset stdout handler to default behavior if necessary |
| 68 | pyodide.setStdout({ batched: (str: string) => console.log(str) }); |
| 69 | |
| 70 | return { result, stdout: stdout_content }; |
| 71 | } catch (error) { |
| 72 | console.error('Loading Pyodide failed', error); |
| 73 | return { error }; |
| 74 | } |
| 75 | } |