What is an alternative to execfile in Python 3?

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

    As suggested on the python-dev mailinglist recently, the runpy module might be a viable alternative. Quoting from that message:

    https://docs.python.org/3/library/runpy.html#runpy.run_path

    import runpy
    file_globals = runpy.run_path("file.py")
    

    There are subtle differences to execfile:

    • run_path always creates a new namespace. It executes the code as a module, so there is no difference between globals and locals (which is why there is only a init_globals argument). The globals are returned.

      execfile executed in the current namespace or the given namespace. The semantics of locals and globals, if given, were similar to locals and globals inside a class definition.

    • run_path can not only execute files, but also eggs and directories (refer to its documentation for details).

提交回复
热议问题