Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python asyncio debugging example

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?

like image 701
Rdbhost Avatar asked May 01 '15 22:05

Rdbhost


People also ask

Is Python Asyncio multithreaded?

Asynchronous programming is a programming paradigm that enables better concurrency, that is, multiple threads running concurrently. In Python, asyncio module provides this capability. Multiple tasks can run concurrently on a single thread, which is scheduled on a single CPU core.

Why is Asyncio better than threads?

Asyncio vs threading: Async runs one block of code at a time while threading just one line of code at a time. With async, we have better control of when the execution is given to other block of code but we have to release the execution ourselves.

How many times should Asyncio run () be called?

It should be used as a main entry point for asyncio programs, and should ideally only be called once. New in version 3.7.

How does Asyncio work in Python?

Async IO takes long waiting periods in which functions would otherwise be blocking and allows other functions to run during that downtime. (A function that blocks effectively forbids others from running from the time that it starts until the time that it returns.)


1 Answers

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
like image 85
Andrew Svetlov Avatar answered Oct 02 '22 14:10

Andrew Svetlov