Skip to content

Commit a375244

Browse files
committed
code for 0x16 Python inside Rust
1 parent 0a385a1 commit a375244

File tree

5 files changed

+57
-0
lines changed

5 files changed

+57
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[package]
2+
name = "inlinepy"
3+
version = "0.1.0"
4+
authors = ["Bedroom Builds"]
5+
edition = "2018"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[dependencies]
10+
inline-python = "0.6.0"
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
nightly
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
use inline_python::python;
2+
3+
fn main() {
4+
let who = "world";
5+
let n = 5;
6+
python! {
7+
for i in range('n):
8+
print(i, "Hello", 'who)
9+
print("Goodbye")
10+
}
11+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
[package]
2+
name = "py_in_rust"
3+
version = "0.1.0"
4+
authors = ["Bedroom Builds"]
5+
edition = "2018"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[dependencies]
10+
11+
[dependencies.pyo3]
12+
version = "0.13.1"
13+
features = ["auto-initialize"]
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
use pyo3::prelude::*;
2+
use pyo3::types::IntoPyDict;
3+
4+
fn main() -> Result<(), ()> {
5+
Python::with_gil(|py| {
6+
main_(py).map_err(|e| {
7+
// We can't display Python exceptions via std::fmt::Display,
8+
// so print the error here manually.
9+
e.print_and_set_sys_last_vars(py);
10+
})
11+
})
12+
}
13+
14+
fn main_(py: Python) -> PyResult<()> {
15+
let sys = py.import("sys")?;
16+
let version: String = sys.get("version")?.extract()?;
17+
let locals = [("os", py.import("os")?)].into_py_dict(py);
18+
let code = "os.getenv('USER') or os.getenv('USERNAME') or 'Unknown'";
19+
let user: String = py.eval(code, None, Some(&locals))?.extract()?;
20+
println!("Hello {}, I'm Python {}", user, version);
21+
Ok(())
22+
}

0 commit comments

Comments
 (0)