What is an alternative to execfile in Python 3?

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

    You are just supposed to read the file and exec the code yourself. 2to3 current replaces

    execfile("somefile.py", global_vars, local_vars)
    

    as

    with open("somefile.py") as f:
        code = compile(f.read(), "somefile.py", 'exec')
        exec(code, global_vars, local_vars)
    

    (The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.)

    See:

    • http://docs.python.org/release/2.7.3/library/functions.html#execfile
    • http://docs.python.org/release/3.2.3/library/functions.html#compile
    • http://docs.python.org/release/3.2.3/library/functions.html#exec

提交回复
热议问题