有人能为我提供一个导入整个模块目录的好方法吗? 我有一个这样的结构:

/Foo
    bar.py
    spam.py
    eggs.py

我尝试通过添加__init__.py并从Foo import *将其转换为一个包,但它没有按我希望的方式工作。


当前回答

将__all__变量添加到__init__.py,包含:

__all__ = ["bar", "spam", "eggs"]

参见http://docs.python.org/tutorial/modules.html

其他回答

包含一个目录下的所有文件:

专为那些无法上手的新手准备的。

Make a folder /home/el/foo and make a file main.py under /home/el/foo Put this code in there: from hellokitty import * spam.spamfunc() ham.hamfunc() Make a directory /home/el/foo/hellokitty Make a file __init__.py under /home/el/foo/hellokitty and put this code in there: __all__ = ["spam", "ham"] Make two python files: spam.py and ham.py under /home/el/foo/hellokitty Define a function inside spam.py: def spamfunc(): print("Spammity spam") Define a function inside ham.py: def hamfunc(): print("Upgrade from baloney") Run it: el@apollo:/home/el/foo$ python main.py spammity spam Upgrade from baloney

import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
for imp, module, ispackage in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
  __import__(module)

我也遇到过这个问题,这是我的解决方案:

import os

def loadImports(path):
    files = os.listdir(path)
    imps = []

    for i in range(len(files)):
        name = files[i].split('.')
        if len(name) > 1:
            if name[1] == 'py' and name[0] != '__init__':
               name = name[0]
               imps.append(name)

    file = open(path+'__init__.py','w')

    toWrite = '__all__ = '+str(imps)

    file.write(toWrite)
    file.close()

这个函数创建一个名为__init__.py的文件(在提供的文件夹中),其中包含一个__all__变量,该变量保存文件夹中的每个模块。

例如,我有一个名为Test的文件夹 它包含:

Foo.py
Bar.py

所以在脚本中,我想把模块导入,我会写:

loadImports('Test/')
from Test import *

这将从Test中导入所有内容,Test中的__init__.py文件现在将包含:

__all__ = ['Foo','Bar']

Anurag Uniyal给出了改进建议!

#!/usr/bin/python
# -*- encoding: utf-8 -*-

import os
import glob

all_list = list()
for f in glob.glob(os.path.dirname(__file__)+"/*.py"):
    if os.path.isfile(f) and not os.path.basename(f).startswith('_'):
        all_list.append(os.path.basename(f)[:-3])

__all__ = all_list  

我有一个嵌套的目录结构,即在包含python模块的主目录中有多个目录。

我在__init__.py文件中添加了以下脚本以导入所有模块

import glob, re, os 

module_parent_directory = "path/to/the/directory/containing/__init__.py/file"

owd = os.getcwd()
if not owd.endswith(module_parent_directory): os.chdir(module_parent_directory)

module_paths = glob.glob("**/*.py", recursive = True)

for module_path in module_paths:
    if not re.match( ".*__init__.py$", module_path):
        import_path = module_path[:-3]
        import_path = import_path.replace("/", ".")
        exec(f"from .{import_path} import *")

os.chdir(owd)

也许这不是实现这一目标的最佳方式,但除此之外我没有别的办法。