0

I'm giving in command line arguments to a Python script, two of which are the python file name and the class I'd like to import. How can I define the module and import it during runtime in my __main__ function?

Thanks!

ap=argparse.ArgumentParser()
ap.add_argument("-f", "--filename", help="the path to the file where the imaging class is located")
ap.add_argument("-c", "--class", help="name of the class to be imported")


args = vars(ap.parse_args())
filename = args["filename"]
imagingClass = args["class"]

from [filename] import [class] # <-- this part
Will
  • 24,082
  • 14
  • 97
  • 108

2 Answers2

0

For Python 2.7+ it is recommended to use importlib module:

my_module = importlib.import_module("{}.{}".format(args["filename"], args["class"]))

You can also use __import__(), but importlib is the way to go.

try:
    my_module = __import__("{}.{}".format(args["filename"], args["class"]))
except ImportError:
    # An error occurred.
Will
  • 24,082
  • 14
  • 97
  • 108
-1

You can use exec:

exec "from {} import {}".format(filename, imagingClass)

Recommended way is using the importlib though:

my_module = importlib.import_module("{}.{}".format(filename, imagingClass)

You could also use the __import__ function like this:

 my_module = __import__("{}.{}".format(filename, imagingClass))
Peroxy
  • 646
  • 8
  • 18