Python 3 中 execfile 的替代品?
Python 2 有内置函数 execfile
,它是在 Python 3.0 中被删除。 这个问题讨论Python 3.0的替代方案,但有些已进行相当大的更改< a href="http://docs.python.org/py3k/library/importlib.html" rel="noreferrer">自 Python 3.0 起。
Python 3.2 的 execfile
的最佳替代品是什么和未来的 Python 3.x 版本?
Python 2 had the builtin function execfile
, which was removed in Python 3.0. This question discusses alternatives for Python 3.0, but some considerable changes have been made since Python 3.0.
What is the best alternative to execfile
for Python 3.2, and future Python 3.x versions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
2to3
脚本替换为
这似乎是官方推荐。您可能需要使用
with
块来确保文件再次立即关闭:您可以省略
globals
和locals
参数来执行文件,或使用exec(code, {})
使用新的临时字典作为全局和本地字典,从而有效地在新的临时范围中执行文件。The
2to3
script replacesby
This seems to be the official recommendation. You may want to use a
with
block to ensure that the file is promptly closed again:You can omit the
globals
andlocals
arguments to execute the file in the current scope, or useexec(code, {})
to use a new temporary dictionary as both the globals and locals dictionary, effectively executing the file in a new temporary scope.可以替换为
适用于所有版本的 Python
较新版本的 Python 会警告你没有关闭该文件,因此如果你想摆脱该警告,你可以这样做:
但实际上,如果你关心关闭文件时,您应该足够小心,不要首先使用 exec 。
can be replaced with
which works in all versions of Python
Newer versions of Python will warn you that you didn't close that file, so then you can do this is you want to get rid of that warning:
But really, if you care about closing files, you should care enough to not use
exec
in the first place.在Python3.x中,这是我能想到的最接近直接执行文件的方法,它与运行
python /path/to/somefile.py
相匹配。注意:
__main__
,一些脚本依赖于此来检查它们是否正在加载作为模块或不作为例如。if __name__ == "__main__"
__file__
对于异常消息来说更好,并且某些脚本使用__file__
来获取其他文件相对于它们的路径。In Python3.x this is the closest thing I could come up with to executing a file directly, that matches running
python /path/to/somefile.py
.Notes:
__main__
, some scripts depend on this to check if they are loading as a module or not for eg.if __name__ == "__main__"
__file__
is nicer for exception messages and some scripts use__file__
to get the paths of other files relative to them.标准 runpy.run_path 是一种替代方案。
Standard runpy.run_path is an alternative.