[英]Trouble with imp.load_source: 'module' has no attribute 'foo'
I have a directory filled with an arbitrary number of modules, each of which contains only a function do_stuff
. 我有一个目录,目录中充满了任意数量的模块,每个模块仅包含一个函数
do_stuff
。 For example: 例如:
foos/
__init__.py
foo_1.py
foo_2.py
...
foo_n.py
foo_1.py, for example, could just be: 例如,foo_1.py可能是:
def do_stuff(bar):
if bar.blah:
return True
return False
From elsewhere in the code, I want to collect and run all the do_stuff
functions. 从代码的其他地方,我想收集并运行所有的
do_stuff
函数。 I though this would be easy with the imp
module: 我虽然使用
imp
模块会很容易:
import imp
...
...
FOOS_DIR = os.path.join(MY_HOME, 'foos/')
MOD_REGEX = r'^(?!__).*\.py$'
foos = [imp.load_source(fname.split('.py')[0], FOOS_DIR)
for fname in os.listdir(FOOS_DIR)
if re.match(MOD_REGEX, fname)]
results = [foo.do_stuff('argument!') for foo in foos]
However, this leads to: 但是,这导致:
AttributeError: "'module' object has no attribute 'do_stuff'"
From the top answer here , I thought this was the way to go. 从这里的最高答案开始 ,我认为这是要走的路。 If it is, maybe my syntax is off?
如果是这样,也许我的语法关闭了? After all,
load_source
is really forgiving: 毕竟,
load_source
确实是可以原谅的:
(pdb) imp.load_source('not_there', FOOS_DIR)
<module 'not_there' from '/home/blah/blah/foos'>
Otherwise, what could I be missing? 否则,我会丢失什么?
It is indeed a syntax issue! 确实是语法问题! I need the full path to the module file , not just its directory, as the second argument to
load_source
: 我需要模块文件的完整路径,而不仅仅是目录,这是
load_source
的第二个参数:
Thus, 从而,
foos = [imp.load_source(fname.split('.py')[0], FOOS_DIR)
for fname in os.listdir(FOOS_DIR)
if re.match(MOD_REGEX, fname)]
Becomes 变
foos = [imp.load_source(fname.split('.py')[0], '%s%s' % (FOOS_DIR, fname))
for fname in os.listdir(FOOS_DIR)
if re.match(MOD_REGEX, fname)]
And it works just fine! 而且效果很好!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.