python - 如何有条件地从另一个 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
从另一个包有条件地导入和运行脚本的最佳方法是什么?
解决方案
from importlib import import_module
suite = import_module('suites.' + suiteName)
suite.testSuite()
推荐阅读
- python - 在 Plotly Dash 仪表板中允许动态对象创建和删除的最佳方法是什么?
- html - 如何使用 Bootstrap 并排放置卡片?
- javascript - 在数组中查找键
- java - 单击或悬停在分层透明组件上时如何防止奇怪的绘画伪影出现?
- python - 估计矩形物体的姿态是不稳定的
- sql - 查询以检测前一天物品位置的变化(RFID 跟踪)
- html - 使用 go 解析 HTML 中的标签
- python - 根据另一个数组中的可用范围调整一个 numpy 数组
- python - Heroku中的python套接字服务器
- laravel - 访问特定嵌套页面时,VueJS / Laravel 的相对路径不起作用(路由器历史记录开启)