Python asyncio debugging example

11,948

asyncio performs check for PYTHONASYNCIODEBUG on module importing.

Thus you need setup environment variable before very first asyncio import:

import os
os.environ['PYTHONASYNCIODEBUG'] = '1'
import asyncio

# rest of your file
Share:
11,948
Rdbhost
Author by

Rdbhost

Updated on June 06, 2022

Comments

  • Rdbhost
    Rdbhost almost 2 years

    I would like to enable Asyncio's un-yielded coroutine detection, but have not succeeded.

    This simple code implements the recommendations on:
    https://docs.python.org/3/library/asyncio-dev.html#asyncio-logger

    but does not actually catch the un-yielded 'dummy' coroutine.

    import sys, os
    import asyncio
    import logging
    import warnings
    
    os.environ['PYTHONASYNCIODEBUG'] = '1'
    logging.basicConfig(level=logging.DEBUG)
    warnings.resetwarnings()
    
    @asyncio.coroutine
    def dummy():
        print('yeah, dummy ran!!')
    
    @asyncio.coroutine
    def startdummy():
        print('creating dummy')
        dummy()
    
    if __name__ == '__main__':
        lp = asyncio.get_event_loop()
        lp.run_until_complete(startdummy())
    

    I expected that the program would end with a warning about the coroutine 'dummy', created but not yielded from.

    Actually, results are:

    DEBUG:asyncio:Using selector: SelectSelector
    creating dummy
    sys:1: ResourceWarning: unclosed <socket object at 0x02DCB6F0>
    c:\python34\lib\importlib\_bootstrap.py:2150: ImportWarning: sys.meta_path is empty
    sys:1: ResourceWarning: unclosed <socket object at 0x02DE10C0>
    

    No hint of an abandoned coroutine. What am I missing?

  • djh
    djh over 6 years
    s/import sys/import os/
  • gelonida
    gelonida over 4 years
    Is this really true? I found some old project with a comment, that os.environ['PYTHONASYNCIODEBUG'] has to be set before the first call to asyncio.get_event_loop() but not before the first import of asyncio I also don't know (the debug feature for this code hasn't been used tested for quite some time) for which versions of asyncio this code was supposed to run.
  • Andrew Svetlov
    Andrew Svetlov over 4 years
    Now, in 2019, I recommend you to use async/await syntax. It raises a warning regardless of PYTHONASYNCIODEBUG environment variable value.