gpt4 book ai didi

python - Python 3 中 execfile 的替代方案?

转载 作者:IT老高 更新时间:2023-10-28 20:31:24 29 4
gpt4 key购买 nike

Python 2 有内置函数 execfile ,在 Python 3.0 中被删除。 This question讨论 Python 3.0 的替代方案,但有些 considerable changes已制作 since Python 3.0 .

execfile 的最佳替代方案是什么?对于 Python 3.2 和 future Python 3.x versions ?

最佳答案

2to3 脚本替换

execfile(filename, globals, locals)

通过

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

这似乎是官方的建议。您可能需要使用 with block 来确保文件立即再次关闭:

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

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

关于python - Python 3 中 execfile 的替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6357361/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com