[英]Import all modules in a package programatically
我有以下結構:
PACKAGE/
__init__.py
mod1.py
mod2.py
...
code.py
在我的code.py
中,我想導入整個 PACKAGE 文件夾:
import PACKAGE
# execute some functions from mod1, mod2 or ... here.
為確保動態導入,我在__init__.py
中使用以下代碼:
import os
import importlib
for module in os.listdir(os.path.dirname(__file__)):
if module == '__init__.py' or module[-3:] != '.py':
continue
importlib.import_module(module[:-3], package='PACKAGE')
del module
但是,執行code.py
會導致ModuleNotFoundError: No module named 'mod1'
我想知道為什么? 到目前為止,我閱讀了幾次嘗試來實現我想做的事情,但都沒有奏效。 這里的這個似乎對我來說是最有希望的,但我不工作。
我在這里沒有看到什么?
此外,正如評論中提到的那樣, from PACKAGE import *
可以解決問題,但我想保留導入正確包的導入形式,如import PACKAGE
。
你必須 append package 名稱吃到模塊字符串的開頭才能工作,否則它給出了一個no module named <filename> ImportError
。
import os
import importlib
for module in os.listdir(os.path.dirname(__file__)):
if module == '__init__.py' or module[-3:] != '.py':
continue
__import__(__name__+'.'+module[:-3], locals(), globals())
del module
你可以使用 importlib
import os
import importlib
for module in os.listdir(os.path.dirname(__file__)):
if module == '__init__.py' or module[-3:] != '.py':
continue
importlib.import_module("."+module[:-3], __name__ )
del module
最好的方法是列出當前文件夾中的所有 python (.py) 文件,並將它們作為所有變量放入init .py
from os.path import dirname, basename, isfile, join
import glob
modules = glob.glob(join(dirname(__file__), "*.py"))
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.