PyScript⑩(JavaScriptからPyScriptの関数を使う)

JavaScriptからPyScriptの関数を使う

PyodideのランタイムPyScript.runtime)を使うと、JavaScriptからPyScriptの変数だけでなく関数を使用することもできます。

例えばPythonのsort関数を使用するためには、JavaScript内でpyscript.runtime.globals.get('sorted')とし、取得した関数に並べ替えるデータ(配列)を渡します。

[ソースコード]

p2j.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
</head>

<body>

<!-- クリックすると'Apple', 'Banana', 'Candy', 'Donut'を並び変えます。 -->
<button onclick="sortInPython(['Candy', 'Donut', 'Apple', 'Banana'])">Sort In Python And Log</button>
<script>
function sortInPython(data){
js_sorted = pyscript.runtime.globals.get('sorted') // Pythonのsort関数を取得
const sorted_data = js_sorted(data) // Pythonのsort関数を使って並び変え
for (const item of sorted_data){
console.log(item)
}
}
</script>

</body>
</html>

[ブラウザ表示]

ボタンをクリックすると、コンソール(開発ツール)に配列データが並び変えられて表示されることを確認できます。

JavaScriptからPyScriptsort関数を使うことができました。