MCPcopy Create free account
hub / github.com/dgrunwald/rust-cpython / run_code

Method run_code

src/python.rs:281–314  ·  view source on GitHub ↗

Runs code in the given context. `start` indicates the type of input expected: one of `Py_single_input`, `Py_file_input`, or `Py_eval_input`. If `globals` is `None`, it defaults to Python module `__main__`. If `locals` is `None`, it defaults to the value of `globals`.

(
        self,
        code: &str,
        start: c_int,
        globals: Option<&PyDict>,
        locals: Option<&PyDict>,
    )

Source from the content-addressed store, hash-verified

279 /// If `globals` is `None`, it defaults to Python module `__main__`.
280 /// If `locals` is `None`, it defaults to the value of `globals`.
281 fn run_code(
282 self,
283 code: &str,
284 start: c_int,
285 globals: Option<&PyDict>,
286 locals: Option<&PyDict>,
287 ) -> PyResult<PyObject> {
288 let code = CString::new(code).unwrap();
289
290 unsafe {
291 let mptr = ffi::PyImport_AddModule("__main__\0".as_ptr() as *const _);
292
293 if mptr.is_null() {
294 return Err(PyErr::fetch(self));
295 }
296
297 let mdict = ffi::PyModule_GetDict(mptr);
298
299 let globals = match globals {
300 Some(g) => g.as_ptr(),
301 None => mdict,
302 };
303
304 let locals = match locals {
305 Some(l) => l.as_ptr(),
306 None => globals,
307 };
308
309 let res_ptr =
310 ffi::PyRun_StringFlags(code.as_ptr(), start, globals, locals, std::ptr::null_mut());
311
312 err::result_from_owned_ptr(self, res_ptr)
313 }
314 }
315
316 /// Gets the Python builtin value `None`.
317 #[allow(non_snake_case)] // the Python keyword starts with uppercase

Callers 2

evalMethod · 0.80
runMethod · 0.80

Calls 2

result_from_owned_ptrFunction · 0.85
as_ptrMethod · 0.45

Tested by

no test coverage detected