How to modify imported source code on-the-fly?

前端 未结 5 1941
悲哀的现实
悲哀的现实 2020-12-09 17:32

Suppose I have a module file like this:

# my_module.py
print(\"hello\")

Then I have a simple script:

# my_script.py
import          


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 18:18

    If importing the module before the patching it is okay, then a possible solution would be

    import inspect
    
    import my_module
    
    source = inspect.getsource(my_module)
    new_source = source.replace('"hello"', '"world"')
    exec(new_source, my_module.__dict__)
    

    If you're after a more general solution, then you can also take a look at the approach I used in another answer a while ago.

提交回复
热议问题