What is an alternative to execfile in Python 3?

前端 未结 12 1778
滥情空心
滥情空心 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

    While exec(open("filename").read()) is often given as an alternative to execfile("filename"), it misses important details that execfile supported.

    The following function for Python3.x is as close as I could get to having the same behavior as executing a file directly. That matches running python /path/to/somefile.py.

    def execfile(filepath, globals=None, locals=None):
        if globals is None:
            globals = {}
        globals.update({
            "__file__": filepath,
            "__name__": "__main__",
        })
        with open(filepath, 'rb') as file:
            exec(compile(file.read(), filepath, 'exec'), globals, locals)
    
    # execute the file
    execfile("/path/to/somefile.py")
    

    Notes:

    • Uses binary reading to avoid encoding issues
    • Guaranteed to close the file (Python3.x warns about this)
    • Defines __main__, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__"
    • Setting __file__ is nicer for exception messages and some scripts use __file__ to get the paths of other files relative to them.
    • Takes optional globals & locals arguments, modifying them in-place as execfile does - so you can access any variables defined by reading back the variables after running.

    • Unlike Python2's execfile this does not modify the current namespace by default. For that you have to explicitly pass in globals() & locals().

提交回复
热议问题