[英]Python, import functions from modules
我有很多模塊(數百個)。 在每個模塊中,我至少有一個功能。 我的問題是如何只用一行從所有模塊導入所有功能? 因為我不想這樣做:
from tests.test_001 import test_001_func
from tests.test_002 import test_002_func
from tests.test_003 import test_003_func
...
from tests.test_999 import test_999_func
test_xxx是模塊,這些模塊包含test_xxx_func函數,所有模塊都在一個文件夾中。
我想用這樣的東西:
from tests import *
test_001.test_001_func()
但這不起作用
在tests目錄中創建一個__init__.py
文件並在其中放置:
__all__ = [
"test_001_func", "test_002_func", # etc
]
然后你可以:
import tests
tests.test_001_func()
要么
from tests import * # Not the best way to do things.
NB import *
不是首選解決方案的原因是您從調用中刪除了命名空間,因此您可以a)可能與其他模塊中的名稱發生沖突,並且b)您的代碼不太清楚。
您需要通過在包的__init__.py
文件中包含__all__
列表來提供tests
包內容的索引。
在您的情況下, tests
目錄中的__init__.py
文件將具有以下內容:
__all__ == ["test_001", "test_002" <<etc...>>]
請參閱有關從包導入*的文檔。
您可以使用下面的腳本自動導入。
假設文件夾結構是下一個:
run.py
tests
-> test_001.py
-> test_002.py
tests/__init__.py
代碼
import os
import sys
# Append to path "test" folder (also can be any other name)
sys.path.append(os.path.basename(os.path.dirname(__file__)))
__all__ = []
for k in xrange(1, 3):
name = "test_%03d" % k
# __import__ can load module by string name
globals()[name] = __import__(name)
# set that we export only required names like test_001, test_002
__all__.append(name)
test_001.py的代碼:
def test_001_func():
print "test1"
test_002.py的代碼:
def test_002_func():
print "test2"
run.py的代碼: import tests
print tests.test_001
print tests.test_001.test_001_func
print tests.test_002
run.py腳本的輸出將是下一個:
test@test:~/Desktop/python$ python run.py
<module 'test_001' from 'tests/test_001.pyc'>
<function test_001_func at 0xb728b09c>
<module 'test_002' from 'tests/test_002.pyc'>
正如其他答案所指出的那樣,這一切都歸結為填充__all__
,但我想你可以自動完成一些事情:
# In your tests/__init__.py do something along the following lines:
import os.path, pkgutil, importlib
__path = os.path.dirname(__file__)
__all__ = [name for _, name, _ in pkgutil.iter_modules([__path])]
for __module in __all__:
importlib.import_module("." + __module, __name__)
由於importlib
,代碼是Python 2.7+,但是可以使用裸__import__
對過時的Python版本進行修改。
然后像這樣使用它:
import tests
tests.test_002.test_002_func()
要么
from tests import *
test_002.test_002_func()
但是 ,如果這是一個單元測試,我強烈建議考慮看看unittest
或類似的東西鼻子 ,將處理測試中發現一個更Python的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.