8000 RuntimeError: Event loop is closed (_ProactorBasePipeTransport.del, Windows) · Issue #315 · python-kasa/python-kasa · GitHub
[go: up one dir, main page]

Skip to content

RuntimeError: Event loop is closed (_ProactorBasePipeTransport.del, Windows) #315

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
memecode opened this issue Feb 23, 2022 · 16 comments
Closed
Labels
bug Something isn't working stale

Comments

@memecode
Copy link

After installing and running: "kasa --target 192.168.0.255"

I get a bunch of normal output followed by:

Exception ignored in: <function _ProactorBasePipeTransport.del at 0x00000175E0EE6280>
Traceback (most recent call last):
File "c:\program files\python39\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "c:\program files\python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "c:\program files\python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "c:\program files\python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
@rytilahti
Copy link
Member
rytilahti commented Feb 24, 2022

This seems to be a duplicate of #294. Could you please try with the current git master, it should be fixed by #303?

@rytilahti rytilahti added the duplicate This issue or pull request already exists label Feb 24, 2022
@memecode
Copy link
Author

This seems to be a duplicate of #294. Could you please try with the current git master, it should be fixed by #303?

No, I'm still getting the errors with the latest master.

@rytilahti rytilahti added bug Something isn't working and removed duplicate This issue or pull request already exists labels Mar 1, 2022
@rytilahti rytilahti changed the title RuntimeError: Event loop is closed RuntimeError: Event loop is closed (_ProactorBasePipeTransport.del, WSL) Mar 1, 2022
@NameUnrequired
Copy link
NameUnrequired commented Mar 3, 2022

I'm getting the same error with the latest master and a KL130 bulb, when running anything with asyncio

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001F561C68040>
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
  File "C:\Program Files (x86)\Python39\lib\asyncio\proactor_events.py", line 108, in close
  File "C:\Program Files (x86)\Python39\lib\asyncio\base_events.py", line 746, in call_soon
  File "C:\Program Files (x86)\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed

@rytilahti
Copy link
Member
rytilahti commented Mar 22, 2022

Can anyone check if one of these workarounds fixes the issue? Preferably the set_event_loop_policy one. I have no access to windows environments, so I cannot really test it right now.

I'm not sure what's the real solution here (i.e., what should be changed in the socket handling of this lib), but if someone wants to dig and figure it out, that'd be welcome. This aiohttp issue and this python issue could provide some hints where to look at.

@rytilahti rytilahti changed the title RuntimeError: Event loop is closed (_ProactorBasePipeTransport.del, WSL) RuntimeError: Event loop is closed (_ProactorBasePipeTransport.del, Windows) Mar 22, 2022
@kizniche
Copy link
kizniche commented Apr 2, 2022

I am receiving the same error in Linux (why I am stuck using 0.4.0.dev4).

Device: KP303 ({'sw_ver': '1.0.10 Build 200828 Rel.162602', 'hw_ver': '1.0', 'mic_type': 'IOT.SMARTPLUGSWITCH'})
Python 3.9.2
pathon-kasa: 0.4.3

Test code (from kasa.SmartStrip examples):

import asyncio
from kasa import SmartStrip

strip = SmartStrip("192.168.0.35")
asyncio.run(strip.update())

print(f"alias: {strip.alias}: {strip.hw_info}")

for plug in strip.children:
    print(f"{plug.alias}: {plug.is_on}")

asyncio.run(strip.children[1].turn_on())
asyncio.run(strip.update())

print(f"is_on: {strip.is_on}")

Output:

pi@cmdev:~$ ./env/bin/python test_kasa_01.py
alias: TP-LINK_Power Strip_6CAB: {'sw_ver': '1.0.10 Build 200828 Rel.162602', 'hw_ver': '1.0', 'mac': 'REDACTED', 'mic_type': 'IOT.SMARTPLUGSWITCH', 'hwId': 'REDACTED', 'oemId': 'REDACTED'}
Plug 1: False
Plug 2: False
Plug 3: False
Detected protocol reuse between different event loop
Traceback (most recent call last):
  File "/home/pi/env/lib/python3.9/site-packages/kasa/protocol.py", line 138, in _query
    return await asyncio.wait_for(
  File "/usr/lib/python3.9/asyncio/tasks.py", line 481, in wait_for
    return fut.result()
  File "/home/pi/env/lib/python3.9/site-packages/kasa/protocol.py", line 99, in _execute_query
    packed_block_size = await self.reader.readexactly(self.BLOCK_SIZE)
  File "/usr/lib/python3.9/asyncio/streams.py", line 723, in readexactly
    await self._wait_for_data('readexactly')
  File "/usr/lib/python3.9/asyncio/streams.py", line 517, in _wait_for_data
    await self._waiter
RuntimeError: Task <Task pending name='Task-12' coro=<TPLinkSmartHomeProtocol._execute_query() running at /home/pi/env/lib/python3.9/site-packages/kasa/protocol.py:99> cb=[_release_waiter(<Future pendi...xb5f9c448>()]>)() at /usr/lib/python3.9/asyncio/tasks.py:416]> got Future <Future pending> attached to a different loop

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/pi/test_kasa_01.py", line 13, in <module>
    asyncio.run(strip.update())
  File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/home/pi/env/lib/python3.9/site-packages/kasa/smartstrip.py", line 95, in update
    await super().update(update_children)
  File "/home/pi/env/lib/python3.9/site-packages/kasa/smartdevice.py", line 308, in update
    self._last_update = await self.protocol.query(req)
  File "/home/pi/env/lib/python3.9/site-packages/kasa/protocol.py", line 71, in query
    return await self._query(request, retry_count, timeout)
  File "/home/pi/env/lib/python3.9/site-packages/kasa/protocol.py", line 142, in _query
    await self.close()
  File "/home/pi/env/lib/python3.9/site-packages/kasa/protocol.py", line 115, in close
    writer.close()
  File "/usr/lib/python3.9/asyncio/streams.py", line 353, in close
    return self._transport.close()
  File "/usr/lib/python3.9/asyncio/selector_events.py", line 700, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "/usr/lib/python3.9/asyncio/base_events.py", line 746, in call_soon
    self._check_closed()
  File "/usr/lib/python3.9/asyncio/base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Edit: Looks like the docs are out of date. Found this comment useful

@pat-mw
Copy link
pat-mw commented Apr 2, 2022

Any luck fixing this? I'm getting this error on Windows 11 - I installed the repo, I installed the dependencies and tried to run kasa - this works initially but then throws an error
image

@rytilahti
Copy link
Member

See my previous commit if you want to help fixing this, I have no windows so I cannot really test it.

@JacobDel
Copy link

I can testify that this stackoverflow answer solves the error message.
Previous error message:

    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Code:

async def get_bulb():
    bulb = SmartBulb(IP)
    return bulb

async def set_bulb():
    res = get_bulb()
    bulb = await res
    await bulb.update()
    assert bulb.is_bulb

if __name__ == '__main__':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    asyncio.run(set_bulb())

@memecode
Copy link
Author

asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

This is working for me. Although I check the platform first:

if platform.system()=='Windows':

Ideally that requirement to set the event loop policy would be incorporated into python-kasa and the client application wouldn't need to know or care. So I'll leave this open for the moment, unless that's something that CAN'T be added?

@rytilahti
Copy link
Member

I'm open for adding that to the cli tool (if no better solution is found), but the library itself should not touch those settings as the library user may want to use a different policy for a reason or another.

Feel free to open a PR if you wish, otherwise I'll see into that at some point.

@rytilahti
Copy link
Member
rytilahti commented Nov 15, 2022

So I was about to try to find a solution to this, but I am unable to reproduce on Windows 10 using Python 3.10. Both discovery and basic commands I tested (on, off, usage, ..) on HS110 plug seem to function as expected. Tested on the master branch, and with releases 0.4.2 and 0.5.0.

@slashtechno
Copy link
slashtechno commented Dec 11, 2022

I was using Conda with Python version 3.9.12 and I was getting the same error.
I ran conda upgrade python which updated Python to 3.10.8 and I no longer get the error.

@gsehrlich
Copy link
gsehrlich commented Jan 2, 2023

I was using Conda with Python version 3.9.12 and I was getting the same error. I ran conda upgrade python which updated Python to 3.10.8 and I no longer get the error.

Same here (Python version 3.9.7), and this solution worked for me.

Note: this didn't work for me in the base environment, only a conda virtual environment. It seems the most recent version of Anaconda won't upgrade the base environment past Python 3.9.15.

@discdiver
Copy link
discdiver commented Mar 5, 2024

I'm seeing this on Python 3.12, but not 3.11.

My code:

import asyncio
from kasa import SmartPlug


async def update_smart_plug_state(desired_state: bool):
    """Update the state of the smart plug to the desired state

    Args:
        desired_state (bool): The desired state of the smart plug. True for on, False for off
    """

    p = SmartPlug(host="myip")  # Replace with the IP of your device
    # running kasa discover from the CLI gives you the IP and other details

    await p.update()
    print(f"Name of device: {p.alias}")

    if desired_state == True:
        try:
            await p.turn_on()
            print("Device turned on")
        except Exception as e:
            print(f"Error: {e}")
    if desired_state == False:
        try:
            await p.turn_off()
            print("Device turned off")
        except Exception as e:
            print(f"Error: {e}")


if __name__ == "__main__":
    asyncio.run(update_smart_plug_state(True))

Copy link

There hasn't been any activity on this issue recently. This issue has been automatically marked as stale because of that. It will be closed if no further activity occurs.
Please make sure to update to the latest python-kasa version and check if that solves the issue.
Thank you for your contributions.

@github-actions github-actions bot added the stale label Sep 28, 2024
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Oct 6, 2024
@rankinstudio
Copy link
rankinstudio commented Jan 16, 2025

Seeing this issue on latest python-kasa and python 3.11.5 on Windows 11.

Upgrading to python 3.11.11 seems to have fixed it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working stale
Projects
None yet
Development

No branches or pull requests

10 participants
0