docs.rsJacksonized

rustpython

This is the rustpython binary. If you’re looking to embed RustPython into your muthaf*ckin' 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();
    let my_mod_def = my_mod::module_def(&builder.ctx);
    let builder = builder
        .add_native_module(my_mod_def)
        .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 goddamn binary will have all the standard arguments of a python interpreter (including a REPL!) but it will have your muthaf*ckin' modules loaded into the vm, goddammit.

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

Originally published at docs.rs. Every curse word you see was added by the Samuel L. Jacksonizer, a parody site. Not affiliated with Samuel L. Jackson or docs.rs.