RuntimeError: There is no current event loop in thread in async + apscheduler

前端 未结 5 1954
我寻月下人不归
我寻月下人不归 2020-12-12 21:00

I have a async function and need to run in with apscheduller every N minutes. There is a python code below

URL_LIST = [\'\',
            \'

        
5条回答
  •  生来不讨喜
    2020-12-12 21:14

    Since this question continues to appear on the first page, I will write my problem and my answer here.

    I had a RuntimeError: There is no current event loop in thread 'Thread-X'. when using flask-socketio and Bleak.


    Edit: well, I refactored my file and made a class.

    I initialized the loop in the constructor, and now everything is working fine:

    class BLE:
        def __init__(self):
            self.loop = asyncio.get_event_loop()
    
        # function example, improvement of
        # https://github.com/hbldh/bleak/blob/master/examples/discover.py :
        def list_bluetooth_low_energy(self) -> list:
            async def run() -> list:
                BLElist = []
                devices = await bleak.discover()
                for d in devices:
                    BLElist.append(d.name)
                return 'success', BLElist
            return self.loop.run_until_complete(run())
    

    Usage:

    ble = path.to.lib.BLE()
    list = ble.list_bluetooth_low_energy()
    

    Original answer:

    The solution was stupid. I did not pay attention to what I did, but I moved some import out of a function, like this:

    import asyncio, platform
    from bleak import discover
    
    def listBLE() -> dict:
        async def run() -> dict:
            # my code that keep throwing exceptions.
    
        loop = asyncio.get_event_loop()
        ble_list = loop.run_until_complete(run())
        return ble_list
    

    So I thought that I needed to change something in my code, and I created a new event loop using this piece of code just before the line with get_event_loop():

    loop = asyncio.new_event_loop()
    loop = asyncio.set_event_loop()
    

    At this moment I was pretty happy, since I had a loop running.

    But not responding. And my code relied on a timeout to return some values, so it was pretty bad for my app.

    It took me nearly two hours to figure out that the problem was the import, and here is my (working) code:

    def list() -> dict:
        import asyncio, platform
        from bleak import discover
    
        async def run() -> dict:
            # my code running perfectly
    
        loop = asyncio.get_event_loop()
        ble_list  = loop.run_until_complete(run())
        return ble_list
    

提交回复
热议问题