假设A是包目录,B是目录中的模块,X是用B编写的函数或变量。如何使用__import__()语法导入X?以scipy为例:
我想要的:
from scipy.constants.constants import yotta不起作用的是:
>>> __import__("yotta", fromlist="scipy.constants.constants")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("yotta", fromlist=["scipy.constants.constants"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("yotta", fromlist=["scipy","constants","constants"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta
>>> __import__("scipy.constants.constants.yotta", fromlist=["scipy.constants.constats"])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named yotta任何建议都将不胜感激。
发布于 2012-03-03 17:38:26
python import语句执行两个任务:加载模块并使其在名称空间中可用。
import foo.bar.baz 将在名称空间中提供名称foo,而不是baz,因此__import__将提供foo
foo = __import__('foo.bar.baz')另一方面,
from foo.bar.baz import a, b没有使模块可用,但是import语句执行赋值所需的是baz。这对应于
_tmp_baz = __import__('foo.bar.baz', fromlist=['a', 'b'])
a = _tmp_baz.a
b = _tmp_baz.b当然,不会让临时的东西变得可见。
__import__函数并不强制使用a和b,因此当您需要baz时,只需在fromlist参数中输入任何内容,即可将__import__置于"from input“模式。
因此,解决方案如下。假设'yotta‘是一个字符串变量,我使用getattr进行属性访问。
yotta = getattr(__import__('scipy.constants.constants',
fromlist=['yotta']),
'yotta')发布于 2012-03-03 15:19:13
__import__("scipy.constants.constants", fromlist=["yotta"])参数fromlist等同于from LHS import RHS的右侧。
From the docs:
__import__(name[, globals[, locals[, fromlist[, level]]]])
..。
fromlist给出了对象的名称,或子模块应该从name给出的模块导入。
..。
另一方面,语句from spam.ham import eggs, sausage as saus的结果是
_temp = __import__('spam.ham',全局变量(),本地变量(),‘鸡蛋’,‘香肠’,-1)鸡蛋= _temp.eggs saus = _temp.sausage
(重点是我的。)
https://stackoverflow.com/questions/9544331
复制相似问题