简体   繁体   中英

Python Import Hooks and __main__

PEP 302 defines a way for user code to hook into the import process and intercept imports.

However, this only works for imports that occur after some code has run to register the import hook.

Almost by definition, no code runs before the __main__ module, which is the script that is initially run. I haven't had any luck trying to get my import hooks (which do some useful things) to intercept the code being loaded for the __main__ module.

Is there any way forward that I'm missing, or am I just out of luck? I can accept having my import hooks not perform their transformations on the __main__ module, but it would be nice if they did.

Have you tried importing inside main like this?

if __name__ == '__main__':
    import foo
    # Rest of code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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