【问题标题】:Python import module through CLI argument通过 CLI 参数导入 Python 模块
【发布时间】:2020-11-29 14:39:09
【问题描述】:

我想根据 CLI 参数将 python 脚本/模块导入到我的脚本中。我想要这样的东西:

import os
import sys
from sys.argv[1] import ClassName
# Rest of the function using the class ClassName

然后我想从 CLI 调用我想要的任何模块(在我的例子中是机器学习模型):

python3 script.py model_1

有没有办法在 python 中做到这一点?

【问题讨论】:

    标签: python python-3.x command-line-arguments


    【解决方案1】:

    您可以像这样动态导入模块:

    ClassName=__import__(sys.argv[1])
    ClassName.do_something()
    

    import importlib
    ClassName=importlib.import_module(sys.argv[1])
    ClassName.do_something()
    

    它们等于import <The Module> as ClassName

    【讨论】:

    • 感谢您的回答。它虽然没有告诉我如何导入特定的类,例如: import arange from numpy
    • @MNK :同样的东西:arange=importlib.import_module("numpy").arange.如果是模块也可以写成path=importlib.import_module('os.path')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2012-07-14
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多