RuntimeError: Event loop is closed (_ProactorBasePipeTransport.del, Windows)
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
This seems to be a duplicate of #294. Could you please try with the current git master, it should be fixed by #303?
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.
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
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.
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
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

See my previous commit if you want to help fixing this, I have no windows so I cannot really test it.
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())
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?
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.
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.
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.
I was using Conda with Python version 3.9.12 and I was getting the same error. I ran
conda upgrade pythonwhich 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.
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))