Cannot get python to work in my HA setup

Can someone help me setup a really simple python script that writes to a text file in my homeassistant folder? I can’t get this simple action to work. Wondering if I am missing some installation components.

I haven’t gotten into Python scripts in HA yet, but the typical way to write a text file to disk in Python is:

with open('my_file_path', 'w') as file:
  file.write('My text.')

Followed this:

You can use the Home Assistant automation feature to achieve this. Below is a simple YAML script that creates an automation to monitor the state changes of switch.basement_light and append the event and timestamp to a text file in the Home Assistant configuration directory.

yamlCopy code

automation:
  - id: log_basement_light_state_changes
    alias: Log Basement Light State Changes
    trigger:
      platform: state
      entity_id: switch.basement_light
    action:
      service: python_script.log_basement_light_state

Now, create a Python script in the config/python_scripts directory with the name log_basement_light_state.py (you may need to create the python_scripts directory if it doesn’t exist), and add the following content:

pythonCopy code

# log_basement_light_state.py

file_path = "/config/basement_light_log.txt"

event = "on" if data.get("new_state").state == "on" else "off"
timestamp = data.get("new_state").last_updated

with open(file_path, "a") as file:
    file.write(f"Event: {event}, Timestamp: {timestamp}\n")

This script checks whether the switch.basement_light is turning on or off, and then appends the corresponding event and timestamp to a text file (basement_light_log.txt) in the Home Assistant configuration directory.

Make sure to adjust the file_path variable if your configuration directory is located elsewhere.

And got the following error in my log:

Logger: homeassistant.components.python_script.log_basement_light_state.py
Source: components/python_script/__init__.py:224
Integration: Python Scripts (documentation, issues)
First occurred: 11:32:17 PM (2 occurrences)
Last logged: 11:32:18 PM

Error executing script: name 'open' is not defined
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/python_script/__init__.py", line 224, in execute
    exec(compiled.code, restricted_globals)  # noqa: S102
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "log_basement_light_state.py", line 8, in <module>
NameError: name 'open' is not defined

For some reason the built-in open is not being recognized. Check this guy that was having the same error: How to read a specific byte(s) from a binairy file - #18 by happybacon

1 Like