How to avoid using files to store intermediate results

André andre.roberge at gmail.com
Tue Apr 25 21:42:25 EDT 2006


I wrote a small wxPython based app to test code snippets.
(google for "python lightning compiler" if you want to see the full
code).

In the basic mode, I redirect the standard input and output and
execute the code taken from the editor window so that the result
appears in the output window.

Here are the 4 main lines of code to accomplish this:

sys.stdout = self.outputWindow
sys.stderr = self.outputWindow
user_code = self.PythonEditor.GetText()
exec user_code in myGlobals

For example, if I have the following situation:
====input window====
print "Hello world!"
====================

the result of running the program will be this:
====output window===
Hello world!
====================

Simple enough :-)  [Actually, there's more to it, but this description
should suffice for illustration purposes.]


Now, I want to be able to test the code using the doctest module.

I can't use exec as doctest.testmod() will be testing my entire
application, not simply the code in the input window!

The solution I chose was to
1. Create a new file which contains the code to be tested with the
appropriate "doctest" call.
2. Run this file with Python, redirecting the result to a second file.
3. Read the result from the second file into a string.
4. Print the string (which, because of redirection) appears in the
output window.

Here are the main lines of code to do this:

sys.stdout = self.outputWindow
sys.stderr = self.outputWindow
user_code = self.PythonEditor.GetText()

user_code += "\nimport doctest\ndoctest.testmod()"

f = open('_doctest_file.py', 'w')
f.write(user_code)
f.close()

if verbose:
   os.popen("python _doctest_file.py -v> _doctest_file.output")
else:
   os.popen("python _doctest_file.py> _doctest_file.output")
result = open("_doctest_file.output", 'r').read()
print result

######
While this works, I find it "messy", as it creates some intermediate
files.  I was wondering if there was a better way to do things all in
memory, in an OS independent way.

[Note that the complete application is approximately 665 lines long
... a bit too much to post all here :-)]

André




More information about the Python-list mailing list