What is an alternative to execfile in Python 3?

前端 未结 12 1978
滥情空心
滥情空心 2020-11-22 02:33

It seems they canceled in Python 3 all the easy way to quickly load a script by removing execfile()

Is there an obvious alternative I\'m missing?

12条回答
  •  甜味超标
    2020-11-22 03:06

    Avoid exec() if you can. For most applications, it's cleaner to make use of Python's import system.

    This function uses built-in importlib to execute a file as an actual module:

    from importlib import util
    
    def load_file_as_module(name, location):
        spec = util.spec_from_file_location(name, location)
        module = util.module_from_spec(spec)
        spec.loader.exec_module(module)
        return module
    

    Usage example

    Let's have a file foo.py:

    def hello():
        return 'hi from module!'
    print('imported from', __file__, 'as', __name__)
    

    And import it as a regular module:

    >>> mod = load_file_as_module('mymodule', './foo.py')
    imported from /tmp/foo.py as mymodule
    >>> mod.hello()
    hi from module!
    >>> type(mod)
    
    

    Advantages

    This approach doesn't pollute namespaces or messes with your $PATH whereas exec() runs code directly in the context of the current function, potentially causing name collisions. Also, module attributes like __file__ and __name__ will be set correctly, and code locations are preserved. So, if you've attached a debugger or if the module raises an exception, you will get usable tracebacks.

    Note that one minor difference from static imports is that the module gets imported (executed) every time you run load_file_as_module(), and not just once as with the import keyword.

提交回复
热议问题