Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'm wrote a main python module that need load a file parser to work, initially I was a only one text parser module, but I need add more parsers for different cases.
parser_class1.py
parser_class2.py
parser_class3.py

Only one is required for every running instance, then I'm thinking load it by command line:

mmain.py -p parser_class1

With this purpose I wrote this code in order to select the parser to load when the main module will be called:

#!/usr/bin/env python

import argparse
aparser = argparse.ArgumentParser()
aparser.add_argument('-p',
            action='store',
            dest='module',
            help='-i module to import')
results = aparser.parse_args()

if not results.module:
    aparser.error('Error! no module')
try:
    exec("import %s" %(results.module))
    print '%s imported done!'%(results.module)
except ImportError, e:
    print e

But, I was reading that this way is dangerous, maybe no stardard..

Then is this approach ok? or I must find another way to do it?
Why?
Thanks, any comment are welcome.

share|improve this question
6  
If you only know what library to import at runtime, you should use __import__ rather than 'exec'. This may be relevant to your case. You also have the importlib module as an option. – Jaime Mar 25 at 16:45
+1 on Jaime's comment. Even then, it's probably OK to import everything, even if you only use one module. – Quentin Pradet May 3 at 6:19

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.