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

前端 未结 5 1940
悲哀的现实
悲哀的现实 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:21

    This doesn't answer the general question of dynamically modifying the source code of an imported module, but to "Override" or "monkey-patch" its use of the print() function can be done (since it's a built-in function in Python 3.x). Here's how:

    #!/usr/bin/env python3
    # my_script.py
    
    import builtins
    
    _print = builtins.print
    
    def my_print(*args, **kwargs):
        _print('In my_print: ', end='')
        return _print(*args, **kwargs)
    
    builtins.print = my_print
    
    import my_module  # -> In my_print: hello
    

提交回复
热议问题