【问题标题】:Python - Replace function in exec and modules imported inside itPython - 替换exec中的函数和其中导入的模块
【发布时间】:2018-06-26 10:45:33
【问题描述】:

我想用exec 替换我运行的代码中的一些内置函数。可以通过在第二个 exec 参数中将其作为字典条目传递。但是,当我尝试在执行的代码中导入模块时,在导入的模块中调用时,函数与原始 bultins 中的函数一样。

这是我想要实现的示例:

from inspect import cleandoc


def new_print(val):
    print('Hello', val)

code_inner = cleandoc("""
    def bar():
        print('Inner')
""")

with open('inner.py', 'w') as f:
    f.write(code_inner)

code_outer = cleandoc("""
    import inner
    print('Outer')
    inner.bar()
""")

exec(code_outer, {'print': new_print}, {})

这是我收到的回复:

Hello Outer
 Inner

这就是我想要的:

Hello Outer
Hello Inner

有没有办法将新的全局变量、内置函数或变量列表传递给正在导入的模块?

【问题讨论】:

    标签: python python-3.x exec python-import


    【解决方案1】:

    我不确定这是否正是您想要的,但是将字典参数传递给函数并更新其模块全局变量是可行的。

    code_inner = cleandoc("""
        def bar(d):
            globals().update(d)
            print('Inner')
    """)
    
    
    code_outer = cleandoc("""
        import inner
        print('Outer')
        inner.bar({'print': print})
    """)
    

    或者,无需修改 bar 函数,您可以像这样将其模块传递给全局:

    code_outer = cleandoc("""
        import inner
        inner.print = print
        print('Outer')
        inner.bar()
    """)
    

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 2011-06-14
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多