예제 #1
0
def f():
    micropython.heap_lock()
    try:
        raise ValueError(1)
    except ValueError as er:
        sys.print_exception(er)
    micropython.heap_unlock()
예제 #2
0
def test():
    micropython.heap_lock()
    global global_exc
    global_exc.__traceback__ = None
    try:
        raise global_exc
    except StopIteration:
        print('StopIteration')
    micropython.heap_unlock()
def test():
    micropython.heap_lock()
    global global_exc
    global_exc.__traceback__ = None
    try:
        raise global_exc
    except StopIteration:
        print("StopIteration")
    micropython.heap_unlock()
예제 #4
0
def f():
    micropython.heap_lock()
    try:
        raise ValueError(1)
    except ValueError as er:
        exc = er
    micropython.heap_unlock()

    print(repr(exc))
예제 #5
0
async def main():
    t1 = asyncio.create_task(task(1, 4, 20))
    t2 = asyncio.create_task(task(2, 2, 50))

    micropython.heap_lock()

    print("start")
    await asyncio.sleep_ms(1)
    print("sleep")
    await asyncio.sleep_ms(70)
    print("finish")

    micropython.heap_unlock()
예제 #6
0
def func():
    micropython.heap_lock()
    try:
        # This works as is because traceback is not allocated
        # if not possible (heap is locked, no memory). If heap
        # is not locked, this would allocate a traceback entry.
        # To avoid that, traceback should be warmed up (by raising
        # it once after creation) and then cleared before each
        # raise with:
        # e.__traceback__ = None
        raise e
    except Exception as e2:
        print(e2)
    micropython.heap_unlock()
def func():
    micropython.heap_lock()
    try:
        # This works as is because traceback is not allocated
        # if not possible (heap is locked, no memory). If heap
        # is not locked, this would allocate a traceback entry.
        # To avoid that, traceback should be warmed up (by raising
        # it once after creation) and then cleared before each
        # raise with:
        # e.__traceback__ = None
        raise e
    except Exception as e2:
        print(e2)
    micropython.heap_unlock()
예제 #8
0
def f():
    micropython.heap_lock()
    try:
        raise ValueError(1)
    except ValueError as er:
        exc = er
    micropython.heap_unlock()

    # print the exception
    buf = uio.StringIO()
    sys.print_exception(exc, buf)
    for l in buf.getvalue().split("\n"):
        if l.startswith("  File "):
            print(l.split('"')[2])
        else:
            print(l)
예제 #9
0
def f():
    micropython.heap_lock()
    try:
        raise ValueError(1)
    except ValueError as er:
        exc = er
    micropython.heap_unlock()

    # print the exception
    buf = uio.StringIO()
    usys.print_exception(exc, buf)
    for l in buf.getvalue().split("\n"):
        if l.startswith("  File "):
            print(l.split('"')[2])
        else:
            print(l)
예제 #10
0
async def main():
    t1 = asyncio.create_task(task(1, 4, 100))
    t2 = asyncio.create_task(task(2, 2, 250))

    # test scheduling tasks, and calling sleep_ms
    micropython.heap_lock()
    print("start")
    await asyncio.sleep_ms(5)
    print("sleep")
    await asyncio.sleep_ms(350)
    print("finish")
    micropython.heap_unlock()

    # test writing to a stream, when the underlying stream is blocked
    s = asyncio.StreamWriter(TestStream(True), None)
    micropython.heap_lock()
    s.write(b"12")
    micropython.heap_unlock()

    # test writing to a stream, when the underlying stream is not blocked
    buf = bytearray(b"56")
    s = asyncio.StreamWriter(TestStream(False), None)
    micropython.heap_lock()
    s.write(b"34")
    s.write(buf)
    micropython.heap_unlock()
예제 #11
0
def record_match():
    # Включим красный(1) светодиод
    pyb.LED(1).on()
    print('Начинаю запись в файл...')    
    # Получим глобальные переменные
    global u
    global counterfiles
    global filename
    global record   

    # Разблокируем кучу иначе впадём в нехватку памяти
    micropython.heap_unlock()
    # Откроем файл и запишем данные
    with open(filename, 'w') as f:
        for record in u:
            f.write(record[0] + record[1] + '\n')
    print('Запись в файл ' + filename + ' успешно завершена!')
    # Заблокируем кучу как и было
    micropython.heap_lock()
    
    # Выключим красный(1) светодиод
    pyb.LED(1).off()
예제 #12
0
def test():
    micropython.heap_lock()

    try:
        name()
    except NameError as e:
        print(type(e).__name__, e)

    try:
        raise 0
    except TypeError as e:
        print(type(e).__name__, e)

    try:
        name()
    except NameError as e:
        print(e.args[0])

    try:
        raise 0
    except TypeError as e:
        print(e.args[0])

    micropython.heap_unlock()
예제 #13
0
def test(addr):
    alloc_emergency_exception_buf(256)
    s = socket.socket()
    s.connect(addr)
    try:
        s.setblocking(False)
        s = ssl.wrap_socket(s, do_handshake=False)
        heap_lock()
        print("heap is locked")
        while True:
            ret = s.write("foo")
            if ret:
                break
        heap_unlock()
        print("wrap: no exception")
    except OSError as e:
        heap_unlock()
        # mbedtls produces "-29184"
        # axtls produces "RECORD_OVERFLOW"
        ok = "-29184" in str(e) or "RECORD_OVERFLOW" in str(e)
        print("wrap:", ok)
        if not ok:
            print("got exception:", e)
    s.close()
예제 #14
0
def main():
    # create an exception with many args while heap is locked
    # should revert to empty tuple for args
    micropython.heap_lock()
    e = Exception(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
    micropython.heap_unlock()
    print(repr(e))

    # create an exception with a long formatted error message while heap is locked
    # should use emergency exception buffer and truncate the message
    def f():
        pass
    micropython.heap_lock()
    try:
        f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1)
    except Exception as er:
        e = er
    micropython.heap_unlock()
    print(repr(e)[:10])

    # create an exception with a long formatted error message while heap is low
    # should use the heap and truncate the message
    lst = []
    while 1:
        try:
            lst = [lst]
        except MemoryError:
            break
    try:
        f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1)
    except Exception as er:
        e = er
    lst[0] = None
    lst = None
    print(repr(e)[:10])

    # raise a deep exception with the heap locked
    # should use emergency exception and be unable to resize traceback array
    def g():
        g()
    micropython.heap_lock()
    try:
        g()
    except Exception as er:
        e = er
    micropython.heap_unlock()
    print(repr(e)[:13])

    # create an exception on the heap with some traceback on the heap, but then
    # raise it with the heap locked so it can't allocate any more traceback
    exc = Exception('my exception')
    try:
        raise exc
    except:
        pass
    def h(e):
        raise e
    micropython.heap_lock()
    try:
        h(exc)
    except Exception as er:
        e = er
    micropython.heap_unlock()
    print(repr(e))
예제 #15
0
# test some extreme cases of allocating exceptions and tracebacks

import micropython

# SKIP LOPY1 for limitations
if os.uname().sysname == 'LoPy':
    print("SKIP")
    import sys
    sys.exit()

# Check for stackless build, which can't call functions without
# allocating a frame on the heap.
try:
    def stackless(): pass
    micropython.heap_lock(); stackless(); micropython.heap_unlock()
except RuntimeError:
    print("SKIP")
    raise SystemExit

# some ports need to allocate heap for the emergency exception
try:
    micropython.alloc_emergency_exception_buf(256)
except AttributeError:
    pass

def main():
    # create an exception with many args while heap is locked
    # should revert to empty tuple for args
    micropython.heap_lock()
    e = Exception(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
    micropython.heap_unlock()
예제 #16
0
def do_iter(l):
    heap_lock()
    for i in l:
        print(i)
    heap_unlock()
예제 #17
0
t = (1, 2, 3)
l = [1, 2]
d = {1: 2}
s = set((1, ))
fs = frozenset((1, ))
g1 = (100 + x for x in range(2))
g2 = gen_func()

# test containment (both success and failure) with the heap locked
heap_lock()
print(49 in b'123', 255 in b'123')
print(1 in t, -1 in t)
print(1 in l, -1 in l)
print(1 in d, -1 in d)
print(1 in s, -1 in s)
heap_unlock()

# test unpacking with the heap locked
unp0 = unp1 = unp2 = None  # preallocate slots for globals
heap_lock()
unp0, unp1, unp2 = t
print(unp0, unp1, unp2)
heap_unlock()

# test certain builtins with the heap locked
heap_lock()
print(all(t))
print(any(t))
print(min(t))
print(max(t))
print(sum(t))
예제 #18
0
# test super() operations which don't require allocation
import micropython

class A:
    def foo(self):
        print('A foo')
        return 42
class B(A):
    def foo(self):
        print('B foo')
        print(super().foo())

b = B()

micropython.heap_lock()
b.foo()
micropython.heap_unlock()
t = (1, 2, 3)
l = [1, 2]
d = {1:2}
s = {1}
fs = frozenset((1,))
g1 = (100 + x for x in range(2))
g2 = gen_func()

# test containment (both success and failure) with the heap locked
heap_lock()
print(49 in b'123', 255 in b'123')
print(1 in t, -1 in t)
print(1 in l, -1 in l)
print(1 in d, -1 in d)
print(1 in s, -1 in s)
heap_unlock()

# test unpacking with the heap locked
unp0 = unp1 = unp2 = None # preallocate slots for globals
heap_lock()
unp0, unp1, unp2 = t
print(unp0, unp1, unp2)
heap_unlock()

# test certain builtins with the heap locked
heap_lock()
print(all(t))
print(any(t))
print(min(t))
print(max(t))
print(sum(t))
예제 #20
0
def main():
    # create an exception with many args while heap is locked
    # should revert to empty tuple for args
    micropython.heap_lock()
    e = Exception(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
    micropython.heap_unlock()
    print(repr(e))

    # create an exception with a long formatted error message while heap is locked
    # should use emergency exception buffer and truncate the message
    def f():
        pass
    micropython.heap_lock()
    try:
        f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1)
    except Exception as er:
        e = er
    micropython.heap_unlock()
    print(repr(e)[:10])

    # create an exception with a long formatted error message while heap is low
    # should use the heap and truncate the message
    lst = []
    while 1:
        try:
            lst = [lst]
        except MemoryError:
            break
    try:
        f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1)
    except Exception as er:
        e = er
    lst[0] = None
    lst = None
    print(repr(e)[:10])

    # raise a deep exception with the heap locked
    # should use emergency exception and be unable to resize traceback array
    def g():
        g()
    micropython.heap_lock()
    try:
        g()
    except Exception as er:
        e = er
    micropython.heap_unlock()
    print(repr(e)[:13])

    # create an exception on the heap with some traceback on the heap, but then
    # raise it with the heap locked so it can't allocate any more traceback
    exc = Exception('my exception')
    try:
        raise exc
    except:
        pass
    def h(e):
        raise e
    micropython.heap_lock()
    try:
        h(exc)
    except Exception as er:
        e = er
    micropython.heap_unlock()
    print(repr(e))
# test super() operations which don't require allocation
import micropython


class A:
    def foo(self):
        print('A foo')
        return 42


class B(A):
    def foo(self):
        print('B foo')
        print(super().foo())


b = B()

micropython.heap_lock()
b.foo()
micropython.heap_unlock()
예제 #22
0
# test super() operations which don't require allocation
import micropython

# Check for stackless build, which can't call functions without
# allocating a frame on heap.
try:
    def stackless(): pass
    micropython.heap_lock(); stackless(); micropython.heap_unlock()
except RuntimeError:
    print("SKIP")
    raise SystemExit

class A:
    def foo(self):
        print('A foo')
        return 42
class B(A):
    def foo(self):
        print('B foo')
        print(super().foo())

b = B()

micropython.heap_lock()
b.foo()
micropython.heap_unlock()
예제 #23
0
l = []
l2 = list(range(100))

micropython.heap_lock()
micropython.heap_lock()

# general allocation on the heap
try:
    print([])
except MemoryError:
    print('MemoryError')

# expansion of a heap block
try:
    l.extend(l2)
except MemoryError:
    print('MemoryError')

print(micropython.heap_unlock())

# Should still fail
try:
    print([])
except MemoryError:
    print('MemoryError')

micropython.heap_unlock()

# check that allocation works after an unlock
print([])
예제 #24
0
def do_iter(l):
    heap_lock()
    for i in l:
        print(i)
    heap_unlock()