MNK
MNK

Reputation: 664

Python import module through CLI argument

I want to import a python script/module into my script based on CLI arguments. I want something like this:

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

And then I want to call whatever module (a machine learning model in my case) I want from the CLI as:

python3 script.py model_1

Is there a way to do this in python?

Upvotes: 1

Views: 382

Answers (1)

Kahn
Kahn

Reputation: 193

You can dynamic import module like:

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

or

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

They are equal to import <The Module> as ClassName

Upvotes: 1

Related Questions