ARGV and import ?

Richard Jones richard at bizarsoftware.com.au
Tue Oct 9 19:27:12 EDT 2001


On Wednesday 10 October 2001 03:23, Gerhard Häring wrote:
> On Tue, Oct 09, 2001 at 10:07:38AM -0700, J wrote:
> > Hi all,
> >
> > This is my first post to this group & I am also fairly new to python,
> > so please forgive me if this isn't the brightest question or the
> > appropriate venue.
> >
> > I would like to do the following:
> > import a module based on what is typed on the command line.
> >
> > I thought this would work:
> > import sys
> > recipes = sys.argv[1]
> > import recipes
> >
> > But, I get this error:
> > >> ImportError: No module named recipes
> >
> > Is there any way to pass the module name to import through an argv?
>
> I think this is one of the rare cases where an exec statement is
> appropriate:
>
> statement = "import %s as mod" % sys.argv[1]
> exec statement

Nooo. In a language as truly introspective as Python, exec is rarely needed. 
As Steve Holden pointed out, the __import__ builtin function is the way to go.


    Richard




More information about the Python-list mailing list