| [ Web Proxy ] |
| Viewing: https://docs.rs/rustpython | [Back] [Original] |
This is the rustpython binary. If youre looking to embed RustPython into your application,
youre likely looking for the rustpython_vm crate.
You can install rustpython with cargo install rustpython. If youd 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;rustpython interpreter. This function will return std::process::ExitCode
based on the return code of the python code ran through the cli.| Web Proxy Viewer | New URL | Original Page |