[Tutor] StringIO and dictionaries
Bob Gailer
bgailer at alum.rpi.edu
Mon Apr 30 18:43:03 CEST 2007
Necmettin Begiter wrote:
> I want to run an external python script inside my script. So here is what I
> came up with:
>
> Print codename for testing purposes.
> Define an empty dictionary.
> Read the file.
> Do StringIO assignments and run the code.
> Get the outputs and append them to the dictionary.
> Print the outputs for testing purposes.
>
>
> The code:
> codeOut= {}
> codeErr= {}
>
> Print codename for testing purposes:
> print codename
> Note: codename is a parameter that is passed to the function for the first
> parts (keys) of codeOut and codeErr dictionaries; and it prints the given
> name (deneme in this case) correctly.
>
> Read the file:
> localfile= open(filename,'r')
> code2run= localfile.readlines()
> localfile.close()
>
> Do StringIO assignments and run the code:
> codOut= StringIO.StringIO()
> codErr= StringIO.StringIO()
> sys.stdout= codOut
> sys.stderr= codErr
> exec code2run
> sys.stdout= sys.__stdout__
> sys.stderr= sys.__stderr__
>
> Get the outputs and append them to the dictionary.
> erroroutput= codErr.getvalue()
> normaloutput= codOut.getvalue()
> codeOut.append({codename:erroroutput})
>
I'm confused when you "assign" errorputput to codeOut and normaloutput
to codeErr.
Also unclear why you use dictionaries in the first place.
When I run this program from a command prompt I get:
File "begiter.py", line 21, in <module>
codeOut.append({codename:erroroutput})
AttributeError: 'dict' object has no attribute 'append'
However when I run it from my IDE (PythonWin) the traceback does not
show. In fact sys.stdout= sys.__stdout__ does not restore the print to
the interactive window.
So there are 2 problems. Fix the first by either
codeOut.update({codename:erroroutput})
or (preferred):
codeOut[codename]=normaloutput
> codeErr.append({codename:normaloutput})
>
> Print the outputs (just for testing):
> print codename
> print normaloutput
> print erroroutput
> print codeOut
> print codeErr
>
> And I get nothing.
> Is there something I am doing wrong? Because I have read
> the parts on dictionaries and stringio and googled, but I can't find the
> problem. Any comments, suggestions? Or could someone please tell me if there
> is something wrong with my code?
>
>
--
Bob Gailer
510-978-4454
More information about the Tutor
mailing list