What is an alternative to execfile in Python 3?

前端 未结 12 1973
滥情空心
滥情空心 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条回答
  •  Happy的楠姐
    2020-11-22 02:56

    If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?

    If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.

    >>> import sys
    >>> sys.path = ['/path/to/script'] + sys.path
    >>> __import__('test')
    
    >>> __import__('test').run()
    'Hello world!'
    

    test.py:

    def run():
            return "Hello world!"
    

    If you're using Python 3.1 or later, you should also take a look at importlib.

提交回复
热议问题