python和__import__的问题 [英] Problem with python and __import__

查看:92
本文介绍了python和__import__的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起通用标题,一旦我理解了我的问题来源就会改变它
我有以下结构:

Sorry for the generic title, will change it once I understand the source of my problem I have the following structure:

foo/
foo/__init__.py
foo/bar/
foo/bar/__init__.py
foo/bar/some_module.py

当我尝试通过这样做导入some_module时:

When I try to import some_module by doing so:

from foo.bar import some_module

它就像一个魅力。
但这对我没有好处,因为我只知道要在运行时导入的模块的名称。所以,如果我尝试:

it works like a charm. But this is no good for me, since I only know the name of the module to import in runtime. so if I try:

from foo.bar import *
mod=__import__('some_module')

我收到错误消息。难道我做错了什么?有一个更好的方法吗?为什么会这样?

I get an error. Am I doing something wrong? Is there a better way to do this? and why is this happening?

为什么会这样?我不太确定我完全理解python包背后的概念。我认为它们等同于java的包,因此

Why is that? I am not quite sure I completely understand the concept behind python packages. I thought they were equivalent to java's packages and thus

推荐答案

我认为正确的方法是:

mod = __import__('foo.bar', fromlist = ['some_module'])

这样即使'foo.bar'部分也可以在运行时更改。
结果 some_module 将以 mod.some_module 的形式提供;如果你想在一个单独的变量中使用getattr:

This way even the 'foo.bar' part can be changed at runtime. As a result some_modulewill be available as mod.some_module; use getattr if you want it in a separate variable:

the_module = getattr(mod, 'some_module')

这篇关于python和__import__的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆