简体   繁体   English

Python导入挂钩和__main__

[英]Python Import Hooks and __main__

PEP 302 defines a way for user code to hook into the import process and intercept imports. PEP 302定义了一种让用户代码挂接到导入过程并拦截导入的方法。

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. 根据定义,几乎没有代码在__main__模块之前运行,该__main__是最初运行的脚本。 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. 我没有运气试图获取我的导入钩子(它做一些有用的事情)来拦截为__main__模块加载的代码。

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. 我可以接受让我的导入挂钩不在__main__模块上执行其转换的方法,但是如果这样做了,那就太好了。

Have you tried importing inside main like this? 您是否尝试过像这样在main内部导入?

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

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

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