How do I override a Python import?

后端 未结 3 1141
一个人的身影
一个人的身影 2020-12-01 01:58

I\'m working on pypreprocessor which is a preprocessor that takes c-style directives and I\'ve been able to make it work like a traditional preprocessor (it\'s self-consumin

3条回答
  •  死守一世寂寞
    2020-12-01 02:36

    Does this answer your question? The second import does the trick.

    Mod_1.py

    def test_function():
        print "Test Function -- Mod 1"
    

    Mod_2.py

    def test_function():
        print "Test Function -- Mod 2"
    

    Test.py

    #!/usr/bin/python
    
    import sys
    
    import Mod_1
    
    Mod_1.test_function()
    
    del sys.modules['Mod_1']
    
    sys.modules['Mod_1'] = __import__('Mod_2')
    
    import Mod_1
    
    Mod_1.test_function()
    

提交回复
热议问题