[英]Import all files in current directory
我剛剛開始了一個python項目。 目錄結構如下:
/algorithms
----/__init__.py
----/linkedlist
--------/__init__.py
--------/file1.py
--------/file2.py
/tests
----/test_linkedlist
您還可以檢查Github存儲庫 。
在algorithms
下的每個子文件夾中,在__init__
文件中,我逐個包含以下所有文件:
from .file1 import *
from .file2 import *
等等。
我想要實現的任務是使用查詢一起運行所有測試:
python3 -m unittest discover tests
tests目錄中的每個文件都按如下方式啟動:
from algorithms.linkedlist import *
import unittest
現在,如果我想將新文件添加到linkedlist目錄,我創建該文件,然后在__init__
文件中添加另一個from .filename import *
的文件。
如何在__init__
文件中編寫腳本,以便每次創建新文件時,我都不必手動插入導入命令?
那么__init__
在同一個文件夾中? 正如文檔所說,import語句是__import__
函數的語法糖。
所以我們可以使用:
import importlib
import glob
for file in glob.iglob('*.py'):
importlib.__import__(file)
這不起作用的一些原因:
import * from
語法。 使用此代碼,您只能運行file1.test
。 glob
。 我們必須指定實際的工作目錄。 __import__
更喜歡知道模塊名稱。 為了找到我結合的解決方案import * from
功能,從這個答案與pkgutil.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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.