Command line sensor to read from file

I’m trying to get Home Assistant to read the contents of a file using the command_line sensor.
My configuration looks like

- platform: command_line
  command: python3 -c "fo = open('todays_events.txt', 'r');pr = fo.read();print (pr);fo.close()"
  name: Todays Events

and the error I am getting in the log file is

ERROR (Thread-11) [homeassistant.components.sensor.command_line] Command failed: python3 -c “fo = open(‘todays_events.txt’, ‘r’);pr = fo.read();print (pr);fo.close()”

I have made sure that the code I am using as the command works on my venv, as I have read that as being a potential issue in other posts. The “todays_events.txt” file is also readable by anyone.

I can’t quite figure out what the problem is with this, any ideas? Thanks

I can’t see the problem, but would the file sensor do for you?

1 Like

Aha yes, thank you!

Do you happen to know if this file updates in home assistant? Like if I were to make a change to the file, would HA see the change or would I have to restart HA for the change to take effect?

It depends on what you change. From the link

Only the last line of the file is used. This is similar to do $ tail -n 1 sensor.txt on the command-line.

So, if you add a line to the end of the file it will read it when running. Any other change will not be detected…

The file sensor run approx. every 30 seconds and will pick-up the latest changes to file if there are any.

2 Likes