Python 的 __import__ 没有按预期工作
当使用带有点名称的 __import__
时,例如:somepackage.somemodule
,返回的模块不是 somemodule
,返回的任何内容似乎都是大部分都是空的! 这里发生了什么?
When using __import__
with a dotted name, something like: somepackage.somemodule
, the module returned isn't somemodule
, whatever is returned seems to be mostly empty! what's going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
来自
__import__
上的 python 文档:解释一下:
当您请求
somepackage.somemodule
时,__import__
返回somepackage.__init__.py
>,通常是空的。如果您提供
fromlist
(您想要的somemodule
内的变量名称列表,但实际上并未返回),它将返回somemodule
您也可以和我一样,使用他们建议的功能。
注:我问这个问题完全是为了自己回答。 我的代码中有一个大错误,并且误诊了它,我花了很长时间才弄清楚,所以我想我应该帮助 SO 社区解决这个问题,并将我遇到的问题发布在这里。
From the python docs on
__import__
:To paraphrase:
When you ask for
somepackage.somemodule
,__import__
returnssomepackage.__init__.py
, which is often empty.It will return
somemodule
if you providefromlist
(a list of the variable names insidesomemodule
you want, which are not actually returned)You can also, as I did, use the function they suggest.
Note: I asked this question fully intending to answer it myself. There was a big bug in my code, and having misdiagnosed it, it took me a long time to figure it out, so I figured I'd help the SO community out and post the gotcha I ran into here.
python 2.7 有 importlib,虚线路径按预期解析
python 2.7 has importlib, dotted paths resolve as expected
有一个更简单的解决方案,如文档中所述:
如果您只想按名称导入模块(可能在包内),您可以调用 __import__() ,然后在 sys.modules 中查找它:
There is a simpler solution, as explained in the documentation:
If you simply want to import a module (potentially within a package) by name, you can call __import__() and then look it up in sys.modules:
有一些东西可以按照您想要的方式工作:twisted.python.reflect.namedAny:
There is something that works as you want it to:
twisted.python.reflect.namedAny
:对于 python 2.6,我写了这个片段:
For python 2.6, I wrote this snippet:
我所做的方式是
然后我可以访问任何内容
The way I did is
then i can access any content from by