ARGV and import ?

Steve Holden sholden at holdenweb.com
Tue Oct 9 13:14:17 EDT 2001


"J" <geek_girl at mailcity.com> 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?
>
>From the Python Library Reference:

"""
2.3 Built-in Functions
The Python interpreter has a number of functions built into it that are
always available. They are listed here in alphabetical order.

__import__ (name[, globals[, locals[, fromlist]]])
This function is invoked by the import statement. It mainly exists so that
you can replace it with another function that has a compatible interface, in
order to change the semantics of the import statement. For examples of why
and how you would do this, see the standard library modules ihooks and
rexec. See also the built-in module imp, which defines some useful
operations out of which you can build your own __import__() function.
"""

Your problem is that the import statement expects to see the name of the
module, not a name to which the name of the module is bound. That's the same
reason why

    print x

prints the VALUE of x, and not "x". You can use the __import__ function to
import a module whose name you have stored in a variable, but you are
descending towards magic, as the import statement does subtly different
things from simply calling __import__(). You may therefore find other spells
have been cast which affect the way your program operates :-)

Try

    __import__(sys.argv[1])

but also be aware that's a potentially dangerous program in someone else's
hands ... they can import any module they like, and the module is EXECUTED
the first time it's imported.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list