What is an alternative to execfile in Python 3?

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

    Here's what I had (file is already assigned to the path to the file with the source code in both examples):

    execfile(file)
    

    Here's what I replaced it with:

    exec(compile(open(file).read(), file, 'exec'))
    

    My favorite part: the second version works just fine in both Python 2 and 3, meaning it's not necessary to add in version dependent logic.

提交回复
热议问题