Commit 2e5a0432 authored by Michael Droettboom's avatar Michael Droettboom

Support `pyimport` on the Javascript side.

parent bc8b55dc
......@@ -23,7 +23,8 @@ all: build/pyodide.asm.html build/pyodide.js
build/pyodide.asm.html: src/main.bc src/jsimport.bc src/jsproxy.bc src/js2python.bc \
src/pyproxy.bc src/python2js.bc src/runpython.bc root
src/pyimport.bc src/pyproxy.bc src/python2js.bc \
src/runpython.bc root
$(CC) -s EXPORT_NAME="'pyodide'" --bind -o $@ $(filter %.bc,$^) $(LDFLAGS) \
$(foreach d,$(wildcard root/*),--preload-file $d@/$(notdir $d))
......
......@@ -2,6 +2,11 @@
#include "js2python.hpp"
////////////////////////////////////////////////////////////
// JsImport
//
// Makes 'from js import foo' work in Python.
using emscripten::val;
static PyObject *original__import__;
......@@ -97,10 +102,12 @@ int JsImport_Ready() {
if (m == NULL) {
return 1;
}
PyObject *d = PyModule_GetDict(m);
if (d == NULL) {
return 1;
}
original__import__ = PyDict_GetItemString(d, "__import__");
if (original__import__ == NULL) {
return 1;
......@@ -117,14 +124,18 @@ int JsImport_Ready() {
}
m = PyImport_AddModule("__main__");
if (m == NULL)
if (m == NULL) {
return 1;
globals = PyModule_GetDict(m);
}
m = PyImport_AddModule("builtins");
PyDict_Update(globals, PyModule_GetDict(m));
globals = PyModule_GetDict(m);
if (globals == NULL) {
return 1;
}
original_globals = PyDict_Copy(globals);
if (PyDict_Update(globals, d)) {
return 1;
}
return 0;
}
......@@ -5,6 +5,5 @@
int JsImport_Ready();
extern PyObject *globals;
extern PyObject *original_globals;
#endif /* JSIMPORT_H */
......@@ -7,6 +7,7 @@
#include "jsimport.hpp"
#include "jsproxy.hpp"
#include "js2python.hpp"
#include "pyimport.hpp"
#include "pyproxy.hpp"
#include "python2js.hpp"
#include "runpython.hpp"
......@@ -22,6 +23,7 @@ using emscripten::val;
EMSCRIPTEN_BINDINGS(python) {
emscripten::function("runPython", &runPython);
emscripten::function("pyimport", &pyimport);
emscripten::class_<Py>("Py")
.function<val>("call", &Py::call)
.function<val>("getattr", &Py::getattr)
......
#include "js2python.hpp"
#include "jsimport.hpp"
#include "pyimport.hpp"
#include "python2js.hpp"
using emscripten::val;
////////////////////////////////////////////////////////////
// PyImport
//
// Makes `var foo = pyimport('foo')` work in Javascript.
val pyimport(val name) {
PyObject *pyname = jsToPython(name);
PyObject *pyval = PyDict_GetItem(globals, pyname);
if (pyval == NULL) {
return pythonExcToJs();
}
return pythonToJs(pyval);
}
#ifndef PYIMPORT_H
#define PYIMPORT_H
#include <emscripten.h>
#include <emscripten/bind.h>
#include <emscripten/val.h>
emscripten::val pyimport(emscripten::val name);
#endif /* PYIMPORT_H */
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment