Execute code located at the specified filesystem location. path_name -- filesystem location of a Python script, zipfile, or directory containing a top level __main__.py script. Optional arguments: init_globals -- dictionary used to pre-populate the module’s globa
(path_name, init_globals=None, run_name=None)
| 260 | return code |
| 261 | |
| 262 | def run_path(path_name, init_globals=None, run_name=None): |
| 263 | """Execute code located at the specified filesystem location. |
| 264 | |
| 265 | path_name -- filesystem location of a Python script, zipfile, |
| 266 | or directory containing a top level __main__.py script. |
| 267 | |
| 268 | Optional arguments: |
| 269 | init_globals -- dictionary used to pre-populate the module’s |
| 270 | globals dictionary before the code is executed. |
| 271 | |
| 272 | run_name -- if not None, this will be used to set __name__; |
| 273 | otherwise, '<run_path>' will be used for __name__. |
| 274 | |
| 275 | Returns the resulting module globals dictionary. |
| 276 | """ |
| 277 | if run_name is None: |
| 278 | run_name = "<run_path>" |
| 279 | pkg_name = run_name.rpartition(".")[0] |
| 280 | from pkgutil import get_importer |
| 281 | importer = get_importer(path_name) |
| 282 | path_name = os.fsdecode(path_name) |
| 283 | if isinstance(importer, type(None)): |
| 284 | # Not a valid sys.path entry, so run the code directly |
| 285 | # execfile() doesn't help as we want to allow compiled files |
| 286 | code = _get_code_from_file(path_name) |
| 287 | return _run_module_code(code, init_globals, run_name, |
| 288 | pkg_name=pkg_name, script_name=path_name) |
| 289 | else: |
| 290 | # Finder is defined for path, so add it to |
| 291 | # the start of sys.path |
| 292 | sys.path.insert(0, path_name) |
| 293 | try: |
| 294 | # Here's where things are a little different from the run_module |
| 295 | # case. There, we only had to replace the module in sys while the |
| 296 | # code was running and doing so was somewhat optional. Here, we |
| 297 | # have no choice and we have to remove it even while we read the |
| 298 | # code. If we don't do this, a __loader__ attribute in the |
| 299 | # existing __main__ module may prevent location of the new module. |
| 300 | mod_name, mod_spec, code = _get_main_module_details() |
| 301 | with _TempModule(run_name) as temp_module, \ |
| 302 | _ModifiedArgv0(path_name): |
| 303 | mod_globals = temp_module.module.__dict__ |
| 304 | return _run_code(code, mod_globals, init_globals, |
| 305 | run_name, mod_spec, pkg_name).copy() |
| 306 | finally: |
| 307 | try: |
| 308 | sys.path.remove(path_name) |
| 309 | except ValueError: |
| 310 | pass |
| 311 | |
| 312 | |
| 313 | if __name__ == "__main__": |