【问题标题】:Python - Import all files in a directory treePython - 导入目录树中的所有文件
【发布时间】:2014-04-26 09:43:02
【问题描述】:

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

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

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

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

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

在 python 2.7 中有什么好的、简单的方法来解决这个问题?

【问题讨论】:

标签: python django reflection introspection


【解决方案1】:

这是使用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)

【讨论】:

    【解决方案2】:
    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]
    

    【讨论】:

    • 除非我弄错了,否则不会在子目录中导入任何内容。
    • 不肯定,os.walk 可以像您的示例中那样解决树问题,但我想在这里展示的是 import 的用法,它允许使用完全限定的名称...
    猜你喜欢
    • 2016-08-23
    • 2016-10-31
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2019-04-09
    • 2017-09-03
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多