ARGV and import ?

Gerhard Häring gh_pythonlist at gmx.de
Tue Oct 9 13:23:30 EDT 2001


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

The import ... as ... imports the module and immediately "renames" it
(in reality, it works on the dictionary sys.modules). So in the above
example, you can use the imported module with the name "mod".

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id 86AB43C0
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))




More information about the Python-list mailing list