-1

Possible Duplicate:
Dynamic module import in Python

I need a functionality that allows users to import multiple modules from the command line. So first let's set up the code that allows users to pass as many arguments as they want into a list:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("cmd", action="store", nargs='*')
args = parser.parse_args()
args_list = args.cmd

I know you can import as many modules as you want using this syntax:

import sys, os, math

So now I just need to find a way to unstring each element from that list(args_list) of strings with module names so I can do the following:

for el in args_list:
    import unstring(el)
Community
  • 1
  • 1
Bentley4
  • 10,678
  • 25
  • 83
  • 134
  • I tried to explain what I have tried so far in a structured way. Most questions that can be answered can also be researched on your own in a lifetime. Except they could potentially take a huge chunk of time for possibly being a solution somebody accidentally stumbled upon very quickly. So why not share? There are questions of different levels of difficulty, nobody is forcing you to answer this question. Also, the more experience you have in an area, the faster you can find similar solutions. – Bentley4 Sep 07 '12 at 12:06
  • So the standard of facility for you to find things in a given area of expertise might be different in comparison to other people. I can acknowledge that you think I did not search well enough. But I don't agree with your opinion that I have not made any effort at all to search for an existing solution. But I give you +1 for at least stating why you downvote. – Bentley4 Sep 07 '12 at 12:06

2 Answers2

1

Probably you would like to use the builtin __import__ function, e.g. something like this:

__import__(el, globals(), locals())
uhz
  • 2,468
  • 1
  • 20
  • 20
1

Use this:

for el in args_list:
    globals()[el] = __import__(el, globals(), locals())
MostafaR
  • 3,547
  • 1
  • 17
  • 24