Run `run` with main scope.
(
&self,
path: &str,
run: impl FnOnce(&Py<PyDict>) -> PyResult<()>,
)
| 1196 | |
| 1197 | /// Run `run` with main scope. |
| 1198 | fn with_simple_run( |
| 1199 | &self, |
| 1200 | path: &str, |
| 1201 | run: impl FnOnce(&Py<PyDict>) -> PyResult<()>, |
| 1202 | ) -> PyResult<()> { |
| 1203 | let sys_modules = self.sys_module.get_attr(identifier!(self, modules), self)?; |
| 1204 | let main_module = sys_modules.get_item(identifier!(self, __main__), self)?; |
| 1205 | let module_dict = main_module.dict().expect("main module must have __dict__"); |
| 1206 | |
| 1207 | // Track whether we set __file__ (for cleanup) |
| 1208 | let set_file_name = !module_dict.contains_key(identifier!(self, __file__), self); |
| 1209 | if set_file_name { |
| 1210 | module_dict.set_item( |
| 1211 | identifier!(self, __file__), |
| 1212 | self.ctx.new_str(path).into(), |
| 1213 | self, |
| 1214 | )?; |
| 1215 | module_dict.set_item(identifier!(self, __cached__), self.ctx.none(), self)?; |
| 1216 | } |
| 1217 | |
| 1218 | let result = run(&module_dict); |
| 1219 | |
| 1220 | self.flush_io(); |
| 1221 | |
| 1222 | // Cleanup __file__ and __cached__ after execution |
| 1223 | if set_file_name { |
| 1224 | let _ = module_dict.del_item(identifier!(self, __file__), self); |
| 1225 | let _ = module_dict.del_item(identifier!(self, __cached__), self); |
| 1226 | } |
| 1227 | |
| 1228 | result |
| 1229 | } |
| 1230 | |
| 1231 | /// flush_io |
| 1232 | /// |