import from a string

iu2 israelu at elbit.co.il
Tue Nov 3 15:36:08 EST 2009


On Nov 3, 7:49 pm, Matt McCredie <mccre... at gmail.com> wrote:
> iu2 <israelu <at> elbit.co.il> writes:
>
>
>
> > Hi,
>
> > Having a file called funcs.py, I would like to read it into a string,
> > and then import from that string.
> > That is instead of importing from the fie system, I wonder if it's
> > possible to eval the text in the string and treat it as a module.
>
> > For example
>
> > with file('funcs.py') as f: txt = r.read()
> > string_import(txt, 'funcs')  # is string_import possible?
>
> > to have now a module called funcs with the functions defined in
> > funcs.py.
>
> You can do something like this:
>
> import types
> import sys
>
> mymodule = types.ModuleType("mymodule", "Optional Doc-String")
>
> with file('funcs.py') as f:
>     txt = f.read()
> exec txt in globals(), mymodule.__dict__
> sys.modules['mymodule'] = mymodule
>
> Note that you shouldn't exec untrusted code.
> You might also look at the __import__ funciton, which can import by python path.
> You might also look at the imp module.
>
> Matt

Thanks, it seems simpler than I thought.
I don't fully understand , though, the exec statement, how it causes
the string execute in the context of mymodule.



More information about the Python-list mailing list