This article is a reprinted abstract , Please move to the full version :
https://mp.weixin.qq.com/s/YT_HNFDCQ_IyocvBkRNJnA
The following is the translation :
About a year ago , I've released a post called inline-python(https://crates.io/crates/inline-python) Of Rust Class library , It allows you to use python!{ .. } Macros easily put some Python Mix to Rust In the code . In this series , I'll show you the process of developing this class library from scratch .
-1-
preview
If you're not familiar with inline-python Class library , You can do the following :
fn main() {
let who = "world";
let n = 5;
python! {
for i in range('n):
print(i, "Hello", 'who)
print("Goodbye")
}
}
It allows you to Python The code is directly embedded Rust Between lines of code , Even directly in Python The code uses Rust Variable .
We will start with a much simpler case , And then gradually try to achieve this result ( Even more !).
-2-
function Python Code
First , Let's see how to Rust Run in Python Code . Let's try to make the first simple example work :
fn main() {
println!("Hello ...");
run_python("print(\"... World!\")");
}
We can use std::process:: Command to run python Executable file and pass python Code , So as to achieve run_python, But if we want to be able to define and read back Python Variable , Then it's best to start with PyO3 Library starts .
PyO3 For us Python Of Rust binding . It is well packed Python C API, So that we can directly in Rust Chinese and various Python Object interaction .( Even in Rust Written in Python library , But that's another theme .)
its Python::run The function fully meets our needs . It will Python Code as &str, And allows us to use two optional PyDicts To define any variable in the scope . Let's have a try :
fn run_python(code: &str) {
let py = pyo3::Python::acquire_gil(); // Acquire the 'global interpreter lock', as Python is not thread-safe.
py.python().run(code, None, None).unwrap(); // No locals, no globals.
}
$ cargo run
Compiling scratchpad v0.1.0
Finished dev [unoptimized + debuginfo] target(s) in 0.29s
Running `target/debug/scratchpad`
Hello ...
... World!
see , It's a success !
-3-
Rule based macros
Write... In a string Python Not the most convenient way , So we try to improve it . Macros allow us to Rust Custom syntax in , So let's try :
fn main() {
println!("Hello ...");
python! {
print("... World!")
}
}
Macros usually use macro_rules! Define , You can use advanced... Based on things like tags and expressions “ Find and replace ” Rules to define macros .( of macro_rules! For an introduction to Rust Book Macro chapter in , of Rust All the details of the macro can be found in 《Rust Macro's little book 》 Find .)
Please move to the full version :https://mp.weixin.qq.com/s/YT_HNFDCQ_IyocvBkRNJnA