找到项目中的所有python包

时间:2017-01-15 10:40:43

标签: python module githooks

我想编写一些clean up脚本以避免意外的Python导入。

为了更好地理解,我会告诉你我的用例。

有时我们的项目文件夹包含以下内容:

...
my_project/custom.py
my_project/custom/__init__.py
...

如果您尝试导入某些内容:

from my_project.custom import some_func

从自定义目录而不是custom.py文件导入。

我想避免这种情况,如果某些python包的父目录中没有python文件(带有 init .py文件的文件夹),请添加一些检查钩子。

问题是: 查找项目中所有Python包的最简单方法是什么?(所有带 init .py文件的目录)

有许多Python库,如:impmodulefinder,...,但我不确定他们是否可以检查文件夹是否是使用完整路径的python模块(没有加载此包)

作为最终结果,我想做这样的事情:

import os
for folder, sub, files in os.walk('/my/project/root/path'):
    # not sure folder or sub, but it doesn't matter
    if is_python_module(folder):
        # do some stuff

看起来我找到了一些解决方案:

for folder,  sub, file in os.walk(path):
    try:
        _, module, _ = imp.find_module(folder)
        print "Module: %s" % module
    except ImportError:
        pass

如果有更好的解决方案,请随时告诉我们!

2 个答案:

答案 0 :(得分:4)

首先,您会混淆术语:

  • 带有__init__.py文件的目录称为; my_project/custom/是一个Python包
  • 模块是包含Python代码的文件; my_project/custom.py是一个Python模块

其次,我会更好地利用os.walk - 以下代码在其意图中更清晰:

import os
for dirpath, dirnames, filenames in os.walk(some_dir):
    if '__init__.py' in filenames:
        # do stuff

编辑:link到文档

答案 1 :(得分:0)

以下代码可能有用。我编写它是为了帮助理解使用import .... as ...的未记录的遗留代码。它与__init__.py问题没有直接关联,但报告可能有所帮助。它只是迭代你的本地命名空间。

首先,我创建一个名为“spection.py”的模块(你可以称之为任何东西):

"""
Python 2 version
10.1.14

"""
import inspect
import sys
import re

def look():

    for name, val in sys._getframe(1).f_locals.items():

        if inspect.ismodule(val):

            fullnm = str(val)

            if not '(built-in)' in fullnm and \
               not __name__     in fullnm:
                m = re.search(r"'(.+)'.*'(.+)'", fullnm)
                module,path = m.groups()
                print "%-12s maps to %s" % (name, path)

现在,在您希望测试的模块中,您可以在导入后添加,如果您有一个,可能在“main()”中添加:

import spection
spection.look()

如果从名为.py的文件加载模块,那么你应该得到这样的结果:

custom       maps to myproject/custom.pyc

如果从__init__.py运行模块,您将得到以下内容:

custom       maps to myproject/custom/__init__.pyc

该函数应对您调用section.look()时导入的所有模块(内置函数除外)执行此操作。显示.pyc个文件,第一次使用该模块时它将是.py文件。

以下是我用于测试的代码:

import sys
sys.path.append('myproject')
import custom

import spection
spection.look()

希望它有所帮助。

相关问题