Add the ability to use the "with" statement on ESFile.

--HG--
extra : convert_revision : svn%3Aeff31bef-be4a-0410-a8fe-e47997df2690/trunk%4049
issue20
tibs 2008-09-03 09:22:43 +00:00
rodzic 657f94b363
commit 1540f806c6
3 zmienionych plików z 38 dodań i 2 usunięć

Wyświetl plik

@ -35,7 +35,15 @@ def main():
print 'underlying C library, and are not "seen" (or hidden) by doctest.'
print
(failures,tests) = doctest.testfile(filename,verbose=verbose)
# I want to be able to use the "with" statement in the doctests.
# It's not possible to use "from __future__ import with_statement"
# in doctests as such. Instead, one has to add the resulting globals
# to the doctest context. Which seems to be done as follows:
import __future__
extraglobs={'with_statement':__future__.with_statement}
(failures,tests) = doctest.testfile(filename,verbose=verbose,
extraglobs=extraglobs)
testword = "test"
if tests != 1: testword = "tests"

Wyświetl plik

@ -1,6 +1,5 @@
Some tests for the Python binding of the TS tools
=================================================
We shall assume that our standard sample data has been downloaded and expanded
into our sibling ``data`` directory. See the ``../data/setup.sh`` script.
@ -242,6 +241,22 @@ OK. So ``seek()`` returns a tuple of (infile,inpacket), whilst the
what each field means, because it *is* impossible to decide rationally which
order they should come in.
The "with" syntax should also work:
>>> count = 0
>>> with ESFile(test_es_file) as f:
... for unit in f:
... count += 1
... print unit
... if count > 5:
... break
ES unit: start code 00, len 9: 00 00 01 00 01 df ff fb b8
ES unit: start code b5, len 9: 00 00 01 b5 85 45 4b 5d 80
ES unit: start code 01, len 1645: 00 00 01 01 0a b0 10 09...
ES unit: start code 02, len 1634: 00 00 01 02 0a b0 10 09...
ES unit: start code 03, len 16: 00 00 01 03 0a b0 10 07...
ES unit: start code 04, len 15: 00 00 01 04 0a b0 10 02...
// Local Variables:
// tab-width: 8

Wyświetl plik

@ -473,6 +473,19 @@ cdef class ESFile:
self.name = None
self.mode = None
def __enter__(self):
return self
def __exit__(self, etype, value, tb):
if tb is None:
# No exception, so just finish normally
self.close()
else:
# Exception occurred, so tidy up
self.close()
# And allow the exception to be re-raised
return False
# ----------------------------------------------------------------------
# vim: set filetype=python expandtab shiftwidth=4:
# [X]Emacs local variables declaration - place us into python mode