2018-06-21 15:19:34 +00:00
|
|
|
# Using Pyodide from Javascript
|
|
|
|
|
|
|
|
This document describes using Pyodide directly from Javascript. For information
|
|
|
|
about using Pyodide from Iodide, see [Using Pyodide from
|
|
|
|
Iodide](using_pyodide_from_iodide.md).
|
|
|
|
|
|
|
|
## Startup
|
|
|
|
|
|
|
|
Include `pyodide.js` in your project.
|
|
|
|
|
2018-11-08 13:25:33 +00:00
|
|
|
This has a single `Promise` object which bootstraps the Python environment:
|
2018-11-08 22:27:08 +00:00
|
|
|
`languagePluginLoader`. Since this must happen asynchronously, it is a
|
2018-06-21 15:19:34 +00:00
|
|
|
`Promise`, which you must call `then` on to complete initialization. When the
|
|
|
|
promise resolves, pyodide will have installed a namespace in global scope:
|
|
|
|
`pyodide`.
|
|
|
|
|
|
|
|
```javascript
|
2018-11-08 13:25:33 +00:00
|
|
|
languagePluginLoader.then(() => {
|
2018-06-21 15:19:34 +00:00
|
|
|
// pyodide is now ready to use...
|
|
|
|
console.log(pyodide.runPython('import sys\nsys.version'));
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
|
|
|
## Running Python code
|
|
|
|
|
|
|
|
Python code is run using the `pyodide.runPython` function. It takes as input a
|
|
|
|
string of Python code. If the code ends in an expression, it returns the result
|
|
|
|
of the expression, converted to Javascript objects (See [type
|
|
|
|
conversions](type_conversions.md)).
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
pyodide.runPython('import sys\nsys.version'));
|
|
|
|
```
|
|
|
|
|
|
|
|
## Loading packages
|
|
|
|
|
|
|
|
Only the Python standard library and `six` are available after importing
|
|
|
|
Pyodide. To use other libraries, you'll need to load their package using
|
|
|
|
`pyodide.loadPackage`. This downloads the file data over the network (as a
|
|
|
|
`.data` and `.js` index file) and installs the files in the virtual filesystem.
|
|
|
|
|
2018-08-29 08:40:10 +00:00
|
|
|
Packages can be loaded by name, for those included in the official pyodide
|
|
|
|
repository (e.g. `pyodide.loadPackage('numpy')`). It is also possible to load
|
|
|
|
packages from custom URLs (e.g.
|
|
|
|
`pyodide.loadPackage('https://foo/bar/numpy.js')`), in which case the URL must
|
|
|
|
end with `<package-name>.js`.
|
|
|
|
|
|
|
|
When you request a package from the official repository, all of that package's
|
|
|
|
dependencies are also loaded. Dependency resolution is not yet implemented
|
|
|
|
when loading packages from custom URLs.
|
2018-06-21 15:19:34 +00:00
|
|
|
|
2018-09-05 09:28:20 +00:00
|
|
|
Multiple packages can also be loaded in a single call,
|
|
|
|
```js
|
|
|
|
pyodide.loadPackage(['cycler', 'pytz'])
|
|
|
|
```
|
|
|
|
|
2018-06-21 15:19:34 +00:00
|
|
|
`pyodide.loadPackage` returns a `Promise`.
|
|
|
|
|
|
|
|
```javascript
|
|
|
|
pyodide.loadPackage('matplotlib').then(() => {
|
|
|
|
// matplotlib is not available
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
|
|
|
## Complete example
|
|
|
|
|
|
|
|
TODO
|