How to import a module given its name as string

0 votes

I'm writing a Python application that takes as a command as an argument, for example:

$ python command1

I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like:


So I want the application to find the available command modules at runtime and execute the appropriate one.

Nov 24, 2020 in Python by Rajiv
• 8,880 points

1 answer to this question.

0 votes

With Python older than 2.7/3.1, that's pretty much how you do it.

For newer versions, see importlib.import_module for Python 2 and Python 3.

You can use exec if you want to as well.

Or using __import__ you can import a list of modules by doing this:

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)
answered Nov 24, 2020 by Gitika
• 65,930 points

Related Questions In Python

0 votes
1 answer

How to check if a given string matches a particular pattern in Python?

You can use re module of python ...READ MORE

answered Jul 3, 2019 in Python by Neel
• 3,020 points
0 votes
1 answer

How to iterate over a string when there is successive increase in its length?

The following code might help -  mystring = ...READ MORE

answered Jul 22, 2019 in Python by Arvind
• 3,000 points
0 votes
1 answer

How to install biopyhton if import is not recognised as a command by the system?

Hello, For install biopyhton with proper instruction you can ...READ MORE

answered Oct 12, 2020 in Python by Niroj
• 82,780 points
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,249 views
0 votes
0 answers
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
0 votes
1 answer

How to import a module given the full path?

For Python 3.5+ use: import importlib.util spec = importlib.util.spec_from_file_location("", ...READ MORE

answered Nov 25, 2020 in Python by Gitika
• 65,930 points
0 votes
1 answer

Calling a function of a module by using its name (a string).

Assuming module foo with method bar: import foo method_to_call = getattr(foo, 'bar') result ...READ MORE

answered Nov 24, 2020 in Python by Gitika
• 65,930 points