首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何覆盖python脚本文件中的一些赋值?

如何覆盖python脚本文件中的一些赋值?
EN

Stack Overflow用户
提问于 2021-02-03 01:13:25
回答 1查看 37关注 0票数 0

我有一个描述一组对象/变量的python文件。使用file.py的示例

代码语言:javascript
复制
a = 5
b = a+1

我想导入文件的内容,并且能够覆盖某些变量的值:parse_with_overwrite(file.py, {"a": 6})将使当前的locals()包含a=6b=7

当然,与任何python文件一样,并非所有变量都在一行…中描述所以不可能在=符号上拆分每一行。此外,变量的顺序很重要,因为一些变量可能依赖于其他变量。

有没有什么内置的或者库可以帮助我做到这一点?

目前,我通过以下方式获取file.py的内容:

代码语言:javascript
复制
context = {}
with open("file.py", "r") as f:
    # the magic should occur here :-)
    exec(f.read(), None, context)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-03 01:33:36

一种安全的方法是使用ast module来解析文件。然后,您可以修改ast中的节点,最后对其进行编译。

这是一个开始:

代码语言:javascript
复制
import ast

def replace_top_assignments(tree, map):
    for i, node in enumerate(tree.body):
        if not isinstance(node, ast.Assign):
            continue

        for nt in node.targets:
            if not isinstance(nt, ast.Name):
                # deal with tuple assignments a, b = 1, 2
                continue
            if nt.id in map:
                # ok we have to replace this
                if not isinstance(node.value, ast.Constant):
                    # warning it is not assigned a constant
                    continue
                # change value for all targets. this will break a=b=2 with a replace of a = 5
                node.value.value = map[nt.id]

src = """
a = 23
b = a
# todo handle these
# b = c = 2
# r, s = 1, a
# conf = usion = 1  what should happen here if you replace usion with 4 ? is conf 4?

print(a)
print(b)
"""

tree = ast.parse(src)
replace_top_assignments(tree, {'a': 4})
code_obj = compile(tree, 'aaa', mode='exec')
exec(code_obj)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66014429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档