I’ve gathered a lot of information to characterize the problem but, unfortunately, nothing to solve it yet.
The problem persists regardless of the version I have tried. It even persists if I uninstall/re-install the python_script integration.
(I uninstalled the python_script integration, and deleted its related directory, upgraded to 2021.5.5, recreated the directory and re-installed the python_script integration and … the error message persists.)
This is sufficient python code to produce the error message:
test1.py
dt1 = datetime.datetime.strptime("2021-05-20", "%Y-%m-%d").date()
dt2 = datetime.datetime.now().strftime("%Y")
Its the first line’s use of strptime
that causes the error KeyError: '__import__'
.
Error executing script: '__import__'
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/components/python_script/__init__.py", line 221, in execute
exec(compiled.code, restricted_globals)
File "test1.py", line 1, in <module>
KeyError: '__import__'
In contrast, the second line, the one using strftime
, causes the same error message on my second instance of Home Assistant. However, there is precedent for strftime
causing an error:
And as far back as 2017 where it even surprised balloob:
The odd thing is that my first instance of Home Assistant accepts neither strptime
or strftime
whereas my second instance accepts strptime
but not strftime
. How is this even possible when both use the same version of Home Assistant?
Home Assistant’s implementation of RestrictedPython appears to allow for both: