gpt4 book ai didi

python - 导入当前目录下的所有文件

转载 作者:行者123 更新时间:2023-11-28 18:02:47 25 4
gpt4 key购买 nike

我刚刚开始一个 python 项目。目录结构如下:

/algorithms  
----/__init__.py
----/linkedlist
--------/__init__.py
--------/file1.py
--------/file2.py
/tests
----/test_linkedlist

您还可以检查 Github repository .

algorithms 下的每个子文件夹中,在 __init__ 文件中,我对所有文件一一包含以下内容:

from .file1 import *
from .file2 import *

等等。

我要完成的任务是使用查询一起运行所有测试:

python3 -m unittest discover tests

tests 目录中的每个文件开始如下:

from algorithms.linkedlist import *  
import unittest

现在,如果我想向链表目录添加一个新文件,我会创建该文件,然后在 __init__ 文件中添加另一个 from .filename import *

如何在 __init__ 文件中编写脚本,以便每次创建新文件时,都不必手动插入导入命令?

最佳答案

那么 __init__ 是在同一个文件夹中吗?作为docsimport 语句是 __import__ 函数的语法糖。

所以我们可以使用:

import importlib
import glob
for file in glob.iglob('*.py'):
importlib.__import__(file)

这不起作用的一些原因:

  • 您想在模块 中加载函数 - import * from 语法。使用此代码,您只能运行 file1.test
  • 您运行从另一个目录加载的脚本,这混淆了 glob。我们必须指定实际的工作目录。
  • __import__ 更愿意知道模块名称。

为了找到解决方案,我结合了来自 thisimport * from 函数用来自 thispkgutil.walk_packages 回答博客。

import importlib
import pkgutil

def custom_import_all(module_name):
""" Use to dynamically execute from module_name import * """
# get a handle on the module
mdl = importlib.import_module(module_name)

# is there an __all__? if so respect it
if "__all__" in mdl.__dict__:
names = mdl.__dict__["__all__"]
else:
# otherwise we import all names that don't begin with _
names = [x for x in mdl.__dict__ if not x.startswith("_")]

# now drag them in
globals().update({k: getattr(mdl, k) for k in names})


__path__ = pkgutil.extend_path(__path__, __name__)
for importer, modname, ispkg in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
custom_import_all(modname)

关于python - 导入当前目录下的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55041173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com