Freeze and Resume execution

Slawomir Nowaczyk slawek at cs.lth.se
Sun May 23 08:47:00 EDT 2004


On Sun, 23 May 2004 15:13:53 +0200
"Miki Tebeka" <miki.tebeka at zoran.com> wrote:

#> Hello Slawomir,

#> My problem is that the one raising the error is the generator.

Why? Cannot you rewrite your code in such a way that something else is
raising an exception? Looks like a simple wrapping function to me...

#> Something in the lines of:

#> class BufferFull(Exception):
#>     pass
#> 
#> def send_one_bit(bit):
#>     pass
#> 
#> OUT_BUFFER_SIZE = 10
#> def output(bits):
#>     size = 0
#>     for bit in bits:
#>         send_one_bit(bit) # HW call
#>         size += 1
#>         if size == OUT_BUFFER_SIZE:
#>             raise BufferFull # I'd like to resume just after this point
#>             size = 0

OK, I think I understand better now. So how about that:

**********************************************************************

def output_gen(bits):
    size = 0
    for bit in bits:
        send_one_bit(bit) # HW call
        size += 1
        if size == OUT_BUFFER_SIZE:
            yield "BufferFull" # use yield instead of raise here
            size = 0

generator = None
def output():
    res = generator.next()
    if res == "BufferFull": raise BufferFull

def sendall(bits):
    global generator
    generator = output_gen(bits)
    while True:
        try:
            output()
        except BufferFull:
            print "Emptying buffer"
        except StopIteration:
            print "Done sending"
            break

def test():
    sendall("1234567890123456789012")

**********************************************************************

Catching BufferFull and calling output() doesn't need to be in
sendall() function, it can basically be anywhere you want it to be.

Does this do what you want it to do?

-- 
 Best wishes,
   Slawomir Nowaczyk
     ( Slawomir.Nowaczyk at cs.lth.se )

There are 3 kinds of people:  those who can count & those who can't.





More information about the Python-list mailing list