What is an alternative to execfile in Python 3?

前端 未结 12 1781
滥情空心
滥情空心 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 02:44

    This one is better, since it takes the globals and locals from the caller:

    import sys
    def execfile(filename, globals=None, locals=None):
        if globals is None:
            globals = sys._getframe(1).f_globals
        if locals is None:
            locals = sys._getframe(1).f_locals
        with open(filename, "r") as fh:
            exec(fh.read()+"\n", globals, locals)
    

提交回复
热议问题