简体   繁体   English

Python-替换exec中的函数和其中导入的模块

[英]Python - Replace function in exec and modules imported inside it

I want to replace some builtin functions inside the code that I run with exec . 我想用exec运行的代码中替换一些内置函数。 It is possible by passing it as a dictionary entry in the second exec argument. 可以通过将其作为第二个exec参数中的字典条目传递。 But when I try to import a module inside the executed code, the functions are as in original bultins, when called inside imported module. 但是,当我尝试在执行的代码中导入模块时,在导入的模块内部调用时,功能与原始公告一样。

This is the example of what I'm trying to achieve: 这是我要实现的示例:

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}, {})

This is the response that I receive: 这是我收到的答复:

Hello Outer
 Inner

And this is what I would like to have: 这就是我想要的:

Hello Outer
Hello Inner

Is there any way to pass new globals, or builtins, or maybe variable list to the module beeing imported? 有什么方法可以将新的全局变量,内置函数或变量列表传递给导入的模块吗?

I'm not sure if it's quite what you want, but passing a dictionary parameter to the function and updating its modules globals works. 我不确定这是否正是您想要的,但是将字典参数传递给该函数并更新其模块全局变量是可行的。

code_inner = cleandoc("""
    def bar(d):
        globals().update(d)
        print('Inner')
""")


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

Alternatively, without modification of the bar function you can pass its module a global like so: 另外,无需修改bar函数,您可以将其模块传递给全局,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM