◐ Shell
clean mode source ↗

rustpython - Rust

Expand description

This is the rustpython binary. If you’re looking to embed RustPython into your application, you’re likely looking for the rustpython_vm crate.

You can install rustpython with cargo install rustpython. If you’d like to inject your own native modules, you can make a binary crate that depends on the rustpython crate (and probably rustpython_vm, too), and make a main.rs that looks like:

use rustpython::{InterpreterBuilder, InterpreterBuilderExt};
use rustpython_vm::{pymodule, py_freeze};

fn main() -> std::process::ExitCode {
    let builder = InterpreterBuilder::new().init_stdlib();
    // Add a native module using builder.ctx
    let my_mod_def = my_mod::module_def(&builder.ctx);
    let builder = builder
        .add_native_module(my_mod_def)
        // Add a frozen module
        .add_frozen_modules(py_freeze!(source = "def foo(): pass", module_name = "other_thing"));

    rustpython::run(builder)
}

#[pymodule]
mod my_mod {
    use rustpython_vm::builtins::PyStrRef;

    #[pyfunction]
    fn do_thing(x: i32) -> i32 {
        x + 1
    }

    #[pyfunction]
    fn other_thing(s: PyStrRef) -> (String, usize) {
        let new_string = format!("hello from rust, {}!", s);
        let prev_len = s.byte_len();
        (new_string, prev_len)
    }
}

The binary will have all the standard arguments of a python interpreter (including a REPL!) but it will have your modules loaded into the vm.

See rustpython_derive crate for documentation on macros used in the example above.

pub use rustpython_pylib as pylib;
pub use rustpython_vm as vm;
Interpreter
The general interface for the VM
InterpreterBuilder
Configuration builder for constructing an Interpreter.
InstallPipMode
RunMode
InterpreterBuilderExt
Extension trait for InterpreterBuilder to add rustpython-specific functionality.
parse_opts
Create settings by examining command line arguments and environment variables.
run
The main cli of the rustpython interpreter. This function will return std::process::ExitCode based on the return code of the python code ran through the cli.
run_shell
Enter a repl loop