1

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?

asked Nov 29, 2020 at 6:23
0

1 Answer 1

1

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

answered Nov 29, 2020 at 6:31
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. It though does not tell me how to import a specific class, like: import arange from numpy
@MNK :Same thing:arange=importlib.import_module("numpy").arange.if it's a module ,you can also write like path=importlib.import_module('os.path')

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.