Skip to content

Commit 4f1a582

Browse files
committed
Replace py.run string execution with direct sys.stdout API calls
Eliminate per-call re-parsing of Python code and sys import overhead. Surface Python-level errors via eprintln in debug builds.
1 parent fc4a6a0 commit 4f1a582

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

src/utils.rs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,17 @@ pub fn print(s: String) {
104104
#[cfg(feature = "python-bindings")]
105105
pub fn print(s: String) {
106106
use pyo3::prelude::*;
107-
use pyo3::types::{PyDict, PyDictMethods};
108-
let _ = Python::attach(|py| -> PyResult<()> {
109-
let locals = PyDict::new(py);
110-
locals.set_item("s", s)?;
111-
py.run(pyo3::ffi::c_str!("import sys\nprint(s, end='')\nsys.stdout.flush()"), None, Some(&locals))?;
107+
let result = Python::attach(|py| -> PyResult<()> {
108+
let stdout = py.import("sys")?.getattr("stdout")?;
109+
stdout.call_method1("write", (s,))?;
110+
stdout.call_method0("flush")?;
112111
Ok(())
113112
});
113+
if cfg!(debug_assertions) {
114+
if let Err(e) = result {
115+
eprintln!("Python print failed: {e}");
116+
}
117+
}
114118
}
115119

116120
/// Prompts the user and returns the response, if any.

0 commit comments

Comments
 (0)