MCPcopy Index your code
hub / github.com/RustPython/RustPython / run_file

Function run_file

src/lib.rs:160–193  ·  view source on GitHub ↗

pymain_run_file_obj in Modules/main.c

(vm: &VirtualMachine, scope: Scope, path: &str)

Source from the content-addressed store, hash-verified

158
159// pymain_run_file_obj in Modules/main.c
160fn run_file(vm: &VirtualMachine, scope: Scope, path: &str) -> PyResult<()> {
161 // Check if path is a package/directory with __main__.py
162 if let Some(_importer) = get_importer(path, vm)? {
163 vm.insert_sys_path(vm.new_pyobj(path))?;
164 let runpy = vm.import("runpy", 0)?;
165 let run_module_as_main = runpy.get_attr("_run_module_as_main", vm)?;
166 run_module_as_main.call((vm::identifier!(vm, __main__).to_owned(), false), vm)?;
167 return Ok(());
168 }
169
170 // Add script directory to sys.path[0]
171 if !vm.state.config.settings.safe_path {
172 let dir = std::path::Path::new(path)
173 .parent()
174 .and_then(|p| p.to_str())
175 .unwrap_or("");
176 vm.insert_sys_path(vm.new_pyobj(dir))?;
177 }
178
179 #[cfg(feature = "host_env")]
180 {
181 vm.run_any_file(scope, path)
182 }
183 #[cfg(not(feature = "host_env"))]
184 {
185 // In sandbox mode, the binary reads the file and feeds source to the VM.
186 // The VM itself has no filesystem access.
187 let path = if path.is_empty() { "???" } else { path };
188 match std::fs::read_to_string(path) {
189 Ok(source) => vm.run_string(scope, &source, path.to_owned()).map(drop),
190 Err(err) => Err(vm.new_os_error(err.to_string())),
191 }
192 }
193}
194
195fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> {
196 use rustpython_vm::builtins::PyDictRef;

Callers 2

run_rustpythonFunction · 0.85
test_run_scriptFunction · 0.85

Calls 15

newFunction · 0.85
insert_sys_pathMethod · 0.80
new_pyobjMethod · 0.80
to_strMethod · 0.80
run_any_fileMethod · 0.80
run_stringMethod · 0.80
new_os_errorMethod · 0.80
to_stringMethod · 0.80
get_importerFunction · 0.70
ErrClass · 0.50
importMethod · 0.45
get_attrMethod · 0.45

Tested by 1

test_run_scriptFunction · 0.68