Python - 导入目录树中的所有文件

时间:2014-03-19 20:52:39

标签: python django reflection introspection

我想在目录树中导入所有python文件,即如果我们有以下目录结构:

tests/
tests/foo.py
tests/subtests/bar.py

(想象一下,树是任意深度的。)

我想import_all('tests')并加载foo.pybar.py。使用常用模块名称(tests.footests.subtests.bar)导入会很不错,但不是必需的。

我的实际用例是我有一大堆包含django表单的代码;我想确定哪些表单使用特定的字段类。我对上面代码的计划是加载我的所有代码,然后检查所有加载的类以查找表单类。

在python 2.7中,这是一个很好的,简单的方法吗?

2 个答案:

答案 0 :(得分:0)

这是一个使用os.walk的粗略和准备好的版本:

import os
prefix = 'tests/unit'
for dirpath, dirnames, filenames in os.walk(prefix):
    trimmedmods = [f[:f.find('.py')] for f in filenames if not f.startswith('__') and f.find('.py') > 0]
    for m in trimmedmods: 
        mod = dirpath.replace('/','.')+'.'+m
        print mod
        __import__(mod)

答案 1 :(得分:0)

import os

my_dir = '/whatever/directory/'
files = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(my_dir) for f in files if f.endswith('.py')]
modules = [__import__(os.path.splitext(f)[0],globals(),locals(),[],-1) for f in files]
相关问题