# C++ / static library (advanced) ```{note} Most users want the [npm package](npm.md): it contains the runtime, Python and its standard library, and installs further packages at runtime. This page is for projects that deploy the pyjs runtime themselves (the build output of the `pyjs-dev` conda package) or embed pyjs into their own WebAssembly program, as e.g. [xeus-python](https://github.com/jupyter-xeus/xeus-python) does. ``` ## Deploying the prebuilt runtime ### Prerequisites Before we start, let's introduce a few concepts and tools that are used in the pyjs workflow. #### Emscripten-forge [Emscripten-forge](https://github.com/emscripten-forge/recipes) is similar to [conda-forge](https://conda-forge.org/) and provides packages compiled to webassembly using emscripten. #### Empack https://github.com/emscripten-forge/empack is a tool to "pack" conda environments into a set of files that can be consumed by pyjs. ### Steps So we assume there is a directory called `/path/to/deploy` where we will put all files which need to be served to the user. #### Define a conda environment Pyjs has a conda-like workflow. This means the first step is to create an environment with the `pyjs` package installed and all packages required for the project. ```yaml name: my-pyjs-env channels: - https://repo.prefix.dev/emscripten-forge/6x - conda-forge dependencies: - pyjs-dev - numpy ``` The name of the environment can be chosen by the user. The `channels` section specifies the conda channels to use. The emscripten-forge channel (`https://repo.prefix.dev/emscripten-forge/6x`) is mandatory, it provides `pyjs` and all other packages compiled to WebAssembly. The `conda-forge` channel is used for `noarch` (pure Python) packages. `pyjs-dev` contains the pyjs Python module (`pyjs`) and the pyjs runtime (`libpyjs-static`, with `lib_js/pyjs/pyjs_runtime_browser.{js,wasm}`). #### Create the environment Assuming the yaml file above is called `environment.yml` and is in the current directory, the environment can be created using `micromamba`: ```Bash micromamba create -f environment.yml \ --platform emscripten-wasm32 --prefix /path/to/env ``` #### Copy pyjs Copy the pyjs binary from the environment to the deploy directory. This should move pyjs_runtime_browser.js and pyjs_runtime_browser.wasm to the deployment directory. ```Bash cp /path/to/env/lib_js/pyjs/* /path/to/deploy ``` #### Pack the environment After the environment is defined, the next step is to pack the environment using `empack`. ```Bash empack pack env --env-prefix /path/to/env --outdir /path/to/deploy ``` This will create a tarball for each package in the environment and a `empack_env_meta.json` file that describes the environment. #### The html/JavaScript code The last step is to create a html file that loads the pyjs runtime and the packed environment. pyjs itself does not fill the file system: the page writes the environment into it (here with the runtime's extractor, `_extract_archive`, which unpacks tar / zip archives compressed with gzip, bzip2 or zstd), loads shared libraries if it runs in the main thread, and then starts Python with `startPython()`. ```html Pyjs Example

Pyjs Example

``` `startPython()` is synchronous and starts the interpreter once (later calls do nothing): it needs the standard library at `/lib/pythonX.Y` (an error otherwise) and sets up `runPython`, `runPythonAsync`, `pyimport`, `globals`, `toPy` (see {doc}`JavaScript_API`); `startPython({env: {NAME: "value"}})` sets extra environment variables. ## Embedding pyjs in a C++ program Not only can `pyjs` be used as a standalone Python interpreter, but it can also be embedded in a C++ program. This allows you to run Python code in a C++ program. Pyjs is compiled as a static library that can be linked to a C++ program (when compiled with emscripten). The static library `libpyjs` contains the core module `pyjs_core` and the JavaScript part of pyjs (embedded in the library: no `--pre-js` / `--post-js` files). A C / C++ program starts Python with pyjs in it with one function of `pyjs/pyjs.h`, and runs Python code with the C API or e.g. pybind11: ```cpp #include #include int main() { pyjs_initialize("/"); // python (prefix "/") with pyjs in it pybind11::exec("import pyjs\n" "pyjs.js.console.log('hello from python')"); } ``` `pyjs_initialize(python_home)` is what `Module.startPython()` does from JavaScript. `python_home` is Python's prefix in the file system, any directory (the standard library at `/lib/pythonX.Y`), it sets `PYTHONHOME`; `NULL`: `PYTHONHOME` if set, else `/`. Then defaults for `PYTHONPATH` / `LANG` / `LD_LIBRARY_PATH` (`/lib`, where the dynamic linker finds the shared libraries of packages, e.g. numpy's `libopenblas.so`) unless the program set them, Python started, `pyjs` imported, the JavaScript API created on the Module (`runPython`, `runPythonAsync`, `pyimport`, `globals`, `toPy`) and the runtime kept alive (JavaScript events call into Python later). pybind11 works in an interpreter it did not start; it must not finalize it (no `pybind11::scoped_interpreter`). A program that starts Python itself (its own `PyConfig`, `pybind11::initialize_interpreter(...)`, ...) calls two functions around that instead: ```cpp pyjs_init(); // before: registers pyjs_core as builtin module pybind11::initialize_interpreter(); pyjs_bind(); // after: imports pyjs, the JavaScript API ``` A complete example (its own pixi project, pybind11, numpy, Python under the prefix `/python`, the file system filled with emscripten's file packager, run in node): [`examples/embed`](https://github.com/emscripten-forge/pyjs/tree/main/examples/embed). The program must be a main module (`-s MAIN_MODULE=1`). In the CMakeLists.txt file: ```CMake find_package(pyjs ${pyjs_REQUIRED_VERSION} REQUIRED) target_link_libraries(my_target PRIVATE pyjs) # the essential options of pyjs' own runtime (see its CMakeLists.txt) target_link_options(my_target PRIVATE "SHELL: -s MAIN_MODULE=1" "SHELL: -s MODULARIZE=1" "SHELL: -s EXPORT_NAME=createModule" "SHELL: -s FORCE_FILESYSTEM" "SHELL: -s ALLOW_MEMORY_GROWTH=1" "SHELL: -s STACK_SIZE=32mb" "SHELL: -s SUPPORT_LONGJMP" ) ``` (`-fwasm-exceptions`, and `-m64` for wasm64, come with the `pyjs` target.) Such a program fills the file system itself (the archive extractor is part of pyjs' own runtime only, not of the static library), e.g. with [mambajs](https://github.com/emscripten-forge/mambajs), `FS.writeFile` or emscripten's file packager, before Python starts. Shared libraries are not preloaded by pyjs: in the main thread, load them after Python started and before importing them (see above). ```{note} pyjs 6 replaced the pybind11 / embind based core: no `PYBIND11_EMBEDDED_MODULE(pyjs_core, ...)` / `EMSCRIPTEN_BINDINGS` and no `pyjs_PRE_JS_PATH` / `pyjs_POST_JS_PATH` in your program any more. pyjs 5 removed the classic initialization API (`bootstrap_from_empack_packed_environment`, `init_phase_1` / `init_phase_2`, `_untar`, `_install_conda_file`): fill the file system, then `startPython()` (or, from C / C++, `pyjs_initialize()`). ```