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 myapp.py 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:

myapp/
    __init__.py
    commands/
        __init__.py
        command1.py
        command2.py
    foo.py
    bar.py

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

Nov 25, 2020 in Python by Rajiv
• 8,870 points
1,035 views

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 25, 2020 by Gitika
• 65,770 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
1,207 views
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,050 points
696 views
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,840 points
645 views
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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,464 views
0 votes
1 answer
+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,790 points
4,123 views
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("module.name", ...READ MORE

answered Nov 25, 2020 in Python by Gitika
• 65,770 points
2,557 views
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 25, 2020 in Python by Gitika
• 65,770 points
612 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP