似乎他们取消了在Python 3中通过删除execfile()快速加载脚本的所有简单方法
我是否错过了一个明显的选择?
似乎他们取消了在Python 3中通过删除execfile()快速加载脚本的所有简单方法
我是否错过了一个明显的选择?
当前回答
虽然exec(open("filename").read())通常作为execfile("filename")的替代,但它忽略了execfile支持的重要细节。
下面是Python3的函数。x是我能得到的与直接执行文件相同的行为。匹配运行python /path/到/somefile.py。
def execfile(filepath, globals=None, locals=None):
if globals is None:
globals = {}
globals.update({
"__file__": filepath,
"__name__": "__main__",
})
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), globals, locals)
# Execute the file.
execfile("/path/to/somefile.py")
注:
Uses binary file reading to avoid encoding issues. Guaranteed to close the file (Python3.x warns about this). Defines __main__, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__". Setting __file__ is nicer for exception messages and some scripts use __file__ to get the paths of other files relative to them. Takes optional globals & locals arguments, modifying them in-place as execfile does - so you can access any variables defined by reading back the variables after running. Unlike Python2's execfile this does not modify the current namespace by default. For that you have to explicitly pass in globals() & locals().
其他回答
这个更好,因为它从调用者那里获取全局变量和局部变量:
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)
如果你想要加载的脚本和你运行的脚本在同一个目录中,也许“import”就可以了?
如果你需要动态导入代码,内置函数__ import__和模块imp值得一看。
>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'
test.py:
def run():
return "Hello world!"
如果您使用的是Python 3.1或更高版本,还应该看一看importlib。
这是我所拥有的(在两个例子中,file已经被分配到带有源代码的文件的路径):
execfile(file)
下面是我用它替换的:
exec(compile(open(file).read(), file, 'exec'))
我最喜欢的部分是:第二个版本在Python 2和3中都工作得很好,这意味着不需要添加版本相关的逻辑。
此外,虽然不是纯Python解决方案,但如果你正在使用IPython(无论如何你可能应该这样做),你可以:
%run /path/to/filename.py
这同样简单。
虽然exec(open("filename").read())通常作为execfile("filename")的替代,但它忽略了execfile支持的重要细节。
下面是Python3的函数。x是我能得到的与直接执行文件相同的行为。匹配运行python /path/到/somefile.py。
def execfile(filepath, globals=None, locals=None):
if globals is None:
globals = {}
globals.update({
"__file__": filepath,
"__name__": "__main__",
})
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), globals, locals)
# Execute the file.
execfile("/path/to/somefile.py")
注:
Uses binary file reading to avoid encoding issues. Guaranteed to close the file (Python3.x warns about this). Defines __main__, some scripts depend on this to check if they are loading as a module or not for eg. if __name__ == "__main__". Setting __file__ is nicer for exception messages and some scripts use __file__ to get the paths of other files relative to them. Takes optional globals & locals arguments, modifying them in-place as execfile does - so you can access any variables defined by reading back the variables after running. Unlike Python2's execfile this does not modify the current namespace by default. For that you have to explicitly pass in globals() & locals().