首页 > 解决方案 > 如何有条件地从另一个 Python 包中导入和运行方法?

问题描述

我有一个包含多个测试套件的项目。我希望能够指定我想在命令行中运行的套件:

suite=multiplication python3 .

这是我当前的文件结构:

__main__.py
suites/
    __init__.py
    addition.py
    subtraction.py
    multiplication.py
    division.py

套房/__init__.py

__all__ = ['addition', 'subtraction', 'multiplication', 'division']

减法.py

def testSuite():
    # Bunch of tests

__main__.py

import os
import suites

# Get suite name from 'suite=xxx' in command line
suiteName = os.getenv('suite')
# Based on suiteName, load the correct file
suite = suites[suiteName]
# Call the suite loaded from the file
suite()

这会出错:

suite = suites[suiteName]
TypeError: 'module' object is not subscriptable

从另一个包有条件地导入和运行脚本的最佳方法是什么?

标签: python

解决方案


使用importlib.import_module

from importlib import import_module

suite = import_module('suites.' + suiteName)
suite.testSuite()

推荐阅读