Python 3 中 execfile 的替代方案? [英] Alternative to execfile in Python 3?

查看:38
本文介绍了Python 3 中 execfile 的替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2 具有内置函数 execfile,它在 Python 3.0 中被删除.这个问题讨论了 Python 3.0 的替代方案,但一些相当大的变化自 Python 3.0 起.

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.

execfile 的最佳替代品是什么对于 Python 3.2 和 未来的 Python 3.x 版本?

推荐答案

2to3 脚本替换

execfile(filename, globals, locals)

exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)

这个好像是官方推荐的.您可能需要使用 with 块来确保文件再次立即关闭:

This seems to be the official recommendation. You may want to use a with block to ensure that the file is promptly closed again:

with open(filename, "rb") as source_file:
    code = compile(source_file.read(), filename, "exec")
exec(code, globals, locals)

您可以省略 globalslocals 参数以在当前范围内执行文件,或使用 exec(code, {})使用新的临时字典作为全局字典和本地字典,在新的临时范围内有效地执行文件.

You can omit the globals and locals arguments to execute the file in the current scope, or use exec(code, {}) to use a new temporary dictionary as both the globals and locals dictionary, effectively executing the file in a new temporary scope.

这篇关于Python 3 中 execfile 的替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆