Newbie Q: Import code at run-time?

Jason Orendorff jason at jorendorff.com
Mon Feb 25 02:04:51 EST 2002


James Knowles wrote:
> Now I want to generalize the program so that I can pass in
> the name of the Python module with the dictionary definitions
> along with the database type, e.g.
> 
> $ python builddb dbA mysql >dbA-mysql.sql
> $ python builddb dbB ib >dbB-ib.sql

There are a few ways.  Easiest:

import sys
module_name = sys.argv[2]
__import__(module_name)   # Note *double* underscores here
my_module = sys.modules[module_name]

If you don't like that one, check out execfile().

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list