繁体   English   中英

Python,从模块导入函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM