pymain_run_file_obj in Modules/main.c
(vm: &VirtualMachine, scope: Scope, path: &str)
| 158 | |
| 159 | // pymain_run_file_obj in Modules/main.c |
| 160 | fn 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 | |
| 195 | fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> { |
| 196 | use rustpython_vm::builtins::PyDictRef; |