Skip to content

Instantly share code, notes, and snippets.

@kapulkin
Last active March 5, 2021 13:56
Show Gist options
  • Save kapulkin/d79ed647fc075b14b9cd4ca67cc657bb to your computer and use it in GitHub Desktop.
Save kapulkin/d79ed647fc075b14b9cd4ca67cc657bb to your computer and use it in GitHub Desktop.
Pyodide sandbox: Loading csv file into numpy aray
<html>
<head>
</head>
<input type="file" id="fileInput" onchange="handleFiles(this.files)"/>
<div id="pyodide"/>
<body>
<script type="text/javascript">
self.languagePluginUrl = "/python/"
function createObjectURL ( file ) {
if ( window.webkitURL ) {
return window.webkitURL.createObjectURL( file );
} else if ( window.URL && window.URL.createObjectURL ) {
return window.URL.createObjectURL( file );
} else {
return null;
}
}
function handleFiles (files) {
const file = files[0]
const fileUrl = createObjectURL(file)
console.log(fileUrl)
downloadPyodide(function () {
const el = document.getElementById("pyodide")
console.log('py')
el.textContent = pyodide.runPython('import sys\nsys.version')
pyodide.loadPackage(['numpy']).then(() => {
const el = document.getElementById("pyodide")
pyodide.runPython(
`import numpy as np
import pyodide
data = pyodide.open_url("${fileUrl}")
x = np.genfromtxt(data, delimiter=",")
dataList=(-x).tolist()`)
const data = pyodide.pyimport("dataList")
el.textContent = data
console.log(data)
})
})
}
function downloadPyodide (callback) {
const onScriptLoad = function () {
languagePluginLoader.then(function () {
callback(pyodide)
})
}
const scriptElement = document.createElement('script')
scriptElement.type = 'text/javascript'
scriptElement.src = '/python/pyodide.js'
scriptElement.onreadystatechange = onScriptLoad
scriptElement.onload = onScriptLoad
document.head.appendChild(scriptElement)
}
</script>
</body>
</html>
1725 1747
1753 1775
1007 1029
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment