Execute a module's code without importing it. mod_name -- an absolute module name or package name. Optional arguments: init_globals -- dictionary used to pre-populate the module’s globals dictionary before the code is executed. run_name -- if not None, this will
(mod_name, init_globals=None,
run_name=None, alter_sys=False)
| 197 | "__main__", mod_spec) |
| 198 | |
| 199 | def run_module(mod_name, init_globals=None, |
| 200 | run_name=None, alter_sys=False): |
| 201 | """Execute a module's code without importing it. |
| 202 | |
| 203 | mod_name -- an absolute module name or package name. |
| 204 | |
| 205 | Optional arguments: |
| 206 | init_globals -- dictionary used to pre-populate the module’s |
| 207 | globals dictionary before the code is executed. |
| 208 | |
| 209 | run_name -- if not None, this will be used for setting __name__; |
| 210 | otherwise, __name__ will be set to mod_name + '__main__' if the |
| 211 | named module is a package and to just mod_name otherwise. |
| 212 | |
| 213 | alter_sys -- if True, sys.argv[0] is updated with the value of |
| 214 | __file__ and sys.modules[__name__] is updated with a temporary |
| 215 | module object for the module being executed. Both are |
| 216 | restored to their original values before the function returns. |
| 217 | |
| 218 | Returns the resulting module globals dictionary. |
| 219 | """ |
| 220 | mod_name, mod_spec, code = _get_module_details(mod_name) |
| 221 | if run_name is None: |
| 222 | run_name = mod_name |
| 223 | if alter_sys: |
| 224 | return _run_module_code(code, init_globals, run_name, mod_spec) |
| 225 | else: |
| 226 | # Leave the sys module alone |
| 227 | return _run_code(code, {}, init_globals, run_name, mod_spec) |
| 228 | |
| 229 | def _get_main_module_details(error=ImportError): |
| 230 | # Helper that gives a nicer error message when attempting to |
searching dependent graphs…