How do i cast a string to be used as a module?

Yermat loic at fejoz.net
Fri Mar 26 09:02:43 CET 2004


sean a écrit :
> In article <cyH8c.3460$GH3.601 at fed1read07>,
> sean at sands.beach.net (Sean Berry) writes:
> 
>>I don't know that this partilarily bad programming,
>>but I was interested in doing the following.
>>
>>def functionname( module, var1, var2 ):
>>import module
>>
>>I would like to be able to pass the module name
>>as an argument and have the module imported as a result.
>>
>>For instance... functionname( os, "1", 234)
>>
>>Thanks for any help.
> 
> 
> Thanks for the help, and exec("import "+modname)
> does indeed import the module.
> 
> But, what if I want to call a function from within this
> module that takes as an argument the name of a module.
> 
> For example if I was making a module like the following
> 
> import inspect
> 
> def functionname( modname ):
>     exec("import "+modname)
>     s = inspect.getsource( modname )
>     return s
> 
> How do I cast modname as a module name and not as a string?
> 
> Thanks.
> 
> 


 >>> exec("import chunk")
 >>> globals()["chunk"]
<module 'chunk' from 'chunk.pyc'>

or even simplier :

 >>> __import__("chunk")
<module 'chunk' from 'chunk.pyc'>


Yermat




More information about the Python-list mailing list