Last active
February 2, 2024 10:16
-
-
Save ykrods/a9aa6cbb400a32a43c231d6d70f70a0a to your computer and use it in GitHub Desktop.
pyodide メモ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* js -> python でデータを渡す方法 | |
* | |
* ユーザ入力をそのまま runPython(`${x}`) とかすると危なそうなので、変数として渡したい場合 | |
* | |
* 参考: https://pyodide.org/en/stable/usage/type-conversions.html#calling-python-objects-from-javascript | |
*/ | |
const pyodide = await loadPyodide(); | |
pyodide.global.set("x", 1); | |
pyodide.runPython("x * 2"); | |
// グローバル変数を使いたくない場合 | |
// 1. Pythonの関数をjsから呼ぶ | |
const twice = pyodide.runPython(` | |
from pyodide.ffi import to_js | |
def t(x): return to_js(x * 2) | |
t | |
`); | |
console.log(twice(1)); // => 2 | |
// 2. globals オブジェクトを runPythonなどに渡す | |
// globals は PyProxy 型である必要がある | |
let globals = pyodide.toPy({x: 1}); | |
pyodide.runPython("x * 2", { options: globals }); | |
globals.destroy(); | |
// これだと普通にグローバル変数に入ってしまう(期待してる動作?) | |
const globals = pyodide.globals.copy(); | |
globals.set("x", 1); | |
globals.destroy(); | |
pyodide.globals.get("x"); // => 1 |
バージョンアップで名前空間を分けられるようになった。(0.25.0 のいくらか前からからできていた感があるが)
https://pyodide.org/en/stable/usage/faq.html#how-can-i-execute-code-in-a-custom-namespace
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js"></script>
</head>
<body>
Pyodide test page <br>
Open your browser console to see Pyodide output
<script type="text/javascript">
async function main(){
window.pyodide = await loadPyodide();
const scope = window.pyodide.globals.get("dict")();
window.pyodide.runPython(`
import sys
print(sys.version)
`, { globals: scope });
window.pyodide.runPython("print(sys.version)");// Error
scope.destroy();
}
main();
</script>
</body>
</html>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
v0.23.0 で runPython に locals 引数が入ったので楽になったかも
https://pyodide.org/en/stable/project/changelog.html#javascript-api