Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > execute python code and save the stdout as a string

Reply
Thread Tools

execute python code and save the stdout as a string

 
 
jwaixs
Guest
Posts: n/a
 
      06-25-2005
Hello,

I've a question. Can I execute a part of a python code and put it's
output in a string? Something like this:

s = ""
s = exec """print "Hello World" """
print s

Greetz,

Noud

 
Reply With Quote
 
 
 
 
Leif K-Brooks
Guest
Posts: n/a
 
      06-25-2005
jwaixs wrote:
> I've a question. Can I execute a part of a python code and put it's
> output in a string?


>>> import sys
>>> from cStringIO import StringIO
>>>
>>> def exec_and_get_output(code):

... old_stdout = sys.stdout
... sys.stdout = StringIO()
... try:
... exec code in {}, {}
... return sys.stdout.getvalue()
... finally:
... sys.stdout = old_stdout
...
>>> exec_and_get_output("print 'foo'")

'foo\n'
 
Reply With Quote
 
 
 
 
jwaixs
Guest
Posts: n/a
 
      06-27-2005
Thank you, this really looks cool!

 
Reply With Quote
 
 
 
Reply

Thread Tools

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

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


Similar Threads
Thread Thread Starter Forum Replies Last Post
beginner Q: Kernel#puts, STDOUT, $stdout relation Andreas S Ruby 3 12-09-2006 12:39 AM
Problems redirecting STDOUT (NOT sys.stdout) to a pipe. Elad Python 0 03-19-2006 01:30 PM
copy stdout fails with permission denied when stdout is redirected brian.mabry.edwards@gmail.com Perl Misc 2 12-07-2005 10:49 PM
Can i execute aspx file in my asp pag with server.execute method(sorry) Savas Ates ASP General 1 08-17-2004 04:52 PM
shell script stdout to python string? Jeff Learman Python 2 05-20-2004 09:25 PM



Advertisments