Go Back   Velocity Reviews > Newsgroups > Python
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Reply

Python - import from a string

 
Thread Tools Search this Thread
Old 11-03-2009, 12:45 PM   #1
Default import from a string


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.

Thanks



iu2
  Reply With Quote
Old 11-03-2009, 05:49 PM   #2
Matt McCredie
 
Posts: n/a
Default Re: import from a string
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



Matt McCredie
  Reply With Quote
Old 11-03-2009, 08:36 PM   #3
iu2
 
Posts: n/a
Default Re: import from a string
On Nov 3, 7:49*pm, Matt McCredie <mccre...@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.


iu2
  Reply With Quote
Old 11-04-2009, 01:10 AM   #4
Gabriel Genellina
 
Posts: n/a
Default Re: import from a string
En Tue, 03 Nov 2009 17:36:08 -0300, iu2 <> escribió:
> On Nov 3, 7:49 pm, Matt McCredie <mccre...@gmail.com> wrote:
>> iu2 <israelu <at> elbit.co.il> writes:
>>
>> > 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.


>> 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

>
> 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.


Sometimes you don't even require a module, and this is simpler to
understand. Suppose you have a string like this:

txt = """
def foo(x):
print 'x=', x

def bar(x):
return x + x
"""

you may execute it:

py> namespace = {}
py> exec txt in namespace

The resulting namespace contains the foo and bar functions, and you may
call them:

py> namespace.keys()
['__builtins__', 'foo', 'bar']
py> namespace['foo']('hello')
x= hello

exec just executes the string using the given globals dictionary as its
global namespace. Whatever is present in the dictionary is visible in the
executed code as global variables (none in this example). The global names
that the code creates become entries in the dictionary. (foo and bar;
__builtins__ is an implementation detail of CPython). You may supply
separate globals and locals dictionaries.

--
Gabriel Genellina



Gabriel Genellina
  Reply With Quote
Old 11-04-2009, 05:45 AM   #5
iu2
 
Posts: n/a
Default Re: import from a string
On Nov 4, 3:10*am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar> wrote:
> En Tue, 03 Nov 2009 17:36:08 -0300, iu2 <isra...@elbit.co.il> escribió:
>
>
>
>
>
> > On Nov 3, 7:49 pm, Matt McCredie <mccre...@gmail.com> wrote:
> >> iu2 <israelu <at> elbit.co.il> writes:

>
> >> > 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.
> >> 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

>
> > 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.

>
> Sometimes you don't even require a module, and this is simpler to *
> understand. Suppose you have a string like this:
>
> txt = """
> def foo(x):
> * *print 'x=', x
>
> def bar(x):
> * *return x + x
> """
>
> you may execute it:
>
> py> namespace = {}
> py> exec txt in namespace
>
> The resulting namespace contains the foo and bar functions, and you may *
> call them:
>
> py> namespace.keys()
> ['__builtins__', 'foo', 'bar']
> py> namespace['foo']('hello')
> x= hello
>
> exec just executes the string using the given globals dictionary as its *
> global namespace. Whatever is present in the dictionary is visible in the *
> executed code as global variables (none in this example). The global names *
> that the code creates become entries in the dictionary. (foo and bar; *
> __builtins__ is an implementation detail of CPython). You may supply *
> separate globals and locals dictionaries.
>
> --
> Gabriel Genellina- Hide quoted text -
>
> - Show quoted text -


Thanks for the explanation.
What happens if both global and local dictionaries are supplied: where
are the newly created entities created? In the local dict?




iu2
  Reply With Quote
Old 11-04-2009, 06:02 AM   #6
Gabriel Genellina
 
Posts: n/a
Default Re: import from a string
En Wed, 04 Nov 2009 02:45:23 -0300, iu2 <> escribió:
> On Nov 4, 3:10 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar> wrote:


>> txt = """
>> def foo(x):
>> print 'x=', x
>>
>> def bar(x):
>> return x + x
>> """
>>
>> py> namespace = {}
>> py> exec txt in namespace
>> py> namespace.keys()
>> ['__builtins__', 'foo', 'bar']
>> py> namespace['foo']('hello')
>> x= hello


> What happens if both global and local dictionaries are supplied: where
> are the newly created entities created? In the local dict?


The amazing thing about Python is how easy is to experiment in the
interpreter.
Just see it by yourself!

--
Gabriel Genellina



Gabriel Genellina
  Reply With Quote
Old 11-04-2009, 06:51 PM   #7
Terry Reedy
 
Posts: n/a
Default Re: import from a string
Gabriel Genellina wrote:
> En Wed, 04 Nov 2009 02:45:23 -0300, iu2 <> escribió:
>> On Nov 4, 3:10 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar> wrote:

>
>>> txt = """
>>> def foo(x):
>>> print 'x=', x
>>>
>>> def bar(x):
>>> return x + x
>>> """
>>>
>>> py> namespace = {}
>>> py> exec txt in namespace
>>> py> namespace.keys()
>>> ['__builtins__', 'foo', 'bar']
>>> py> namespace['foo']('hello')
>>> x= hello

>
>> What happens if both global and local dictionaries are supplied: where
>> are the newly created entities created? In the local dict?

>
> The amazing thing about Python is how easy is to experiment in the
> interpreter.
> Just see it by yourself!


Hint: they are created in the same namespace they always are (ignoring
nested functions and nonlocal namespaces). But I agree with Gabriel:
just try it. n1,n2={},{}; exec....

Terry Jan Reedy




Terry Reedy
  Reply With Quote
Old 11-05-2009, 05:53 AM   #8
iu2
 
Posts: n/a
Default Re: import from a string
On Nov 4, 8:51*pm, Terry Reedy <tjre...@udel.edu> wrote:
> Gabriel Genellina wrote:
> > En Wed, 04 Nov 2009 02:45:23 -0300, iu2 <isra...@elbit.co.il> escribió:
> >> On Nov 4, 3:10 am, "Gabriel Genellina" <gagsl-...@yahoo.com.ar> wrote:

>
> >>> txt = """
> >>> def foo(x):
> >>> * *print 'x=', x

>
> >>> def bar(x):
> >>> * *return x + x
> >>> """

>
> >>> py> namespace = {}
> >>> py> exec txt in namespace
> >>> py> namespace.keys()
> >>> ['__builtins__', 'foo', 'bar']
> >>> py> namespace['foo']('hello')
> >>> x= hello

>
> >> What happens if both global and local dictionaries are supplied: where
> >> are the newly created entities created? In the local dict?

>
> > The amazing thing about Python is how easy is to experiment in the
> > interpreter.
> > Just see it by yourself!

>
> Hint: they are created in the same namespace they always are (ignoring
> nested functions and nonlocal namespaces). But I agree with Gabriel:
> just try it. n1,n2={},{}; exec....
>
> Terry Jan Reedy- Hide quoted text -
>
> - Show quoted text -


n2


iu2
  Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Give you enough string functions in Java web reporting tool freezea Software 0 10-08-2009 09:03 AM
Java String Problems rbnbenjamin General Help Related Topics 0 02-03-2009 11:02 PM
ASP.NET: Asign Users in Roles(Array.IndexOf(Of String) method) msandlana Software 0 04-25-2008 06:37 AM
Hidden linebreaks in string? VB.NET Jiggy Software 0 04-23-2008 02:18 PM
Cannot import my IE6 Favorites Julie P. Computer Support 11 06-18-2004 07:26 AM




SEO by vBSEO 3.3.2 ©2009, Crawlability, Inc.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46