Pyscript - new integration for easy and powerful Python scripting

First of all, @craigb, let me thank you for this great Addon to HA. In only a few days, it has completely changed my approach to automations and blown the scope of what I consider possible and doable. I was working with NodeRed before, and while it is capable of a lot of things, it’s just so tedious to figure out how to do something a bit more complex. With pyscript, it’s all super easy and straightforward.

I have one question, though, maybe I am to blind to figure it out by myself: can I create an entity from pyscript, that I can manipulate directly from Lovelace? Specifically, I would like to set up enable switches for my various automations.

Any variables withing the pyscript domain can apparently be displayed, but not modified in lovelace.
I tried to create input_booleans from pyscript, and they appear in the UI, but too, can’t be manipulated.

Anything I am missing here?

I am a trying to use the motion_lights app from the pyscript wiki here: Writing an App in Pyscript Β· custom-components/pyscript Wiki Β· GitHub

I have copied the converted code with comments from the wiki page and placed the motion_lights.py file in the apps folder:

/config/configuration.yaml
pyscript: !include pyscript/config.yaml

And placed the motion_lights.py in:
/config/pyscript/apps/motion_lights.py

and in the /config/pyscript/config.yaml I have this config:

pyscript:
  allow_all_imports: true
  apps:
    motion_lights:
      - motion_id: binary_sensor.bevegelsesensor_kjokken
        light_id: light.lys_kjokken
        time_id: input_number.light_timer_5_minutt

The pyscript debug logs config not present:

2023-04-26 13:20:36.536 DEBUG (MainThread) [custom_components.pyscript] reload: yaml, reloading scripts, and restarting

2023-04-26 13:20:36.606 DEBUG (MainThread) [custom_components.pyscript] No new packages to install

2023-04-26 13:20:36.607 DEBUG (SyncWorker_8) [custom_components.pyscript] load_scripts: skipping /config/pyscript/apps/motion_lights.py (app_name=motion_lights) because config not present

Anything I am missing here?

My pyscript functions work well but unfortunately they always run whenever I restart hass (so certain lights will go on or off when some people are sleeping). I would love to be able to stop this from happening. Anybody can give me some directions?

@state_trigger("switch.light_switch")
def switch_trigger():
    task.unique("switch_trigger", True)
    # DO SOMETHING
    pass

After reading the documentation here: Reference β€” hacs-pyscript 1.5.0 documentation I found out the pyscript yaml configuration must be placed in /config/configuration.yaml like this:

# File includes
group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
pyscript: !include pyscript/config.yaml

logger:
  default: info
  logs:
    custom_components.pyscript: debug

Then I removed pyscript: in the pyscript configuration file /config/pyscript/config.yaml and adjusted the indention like this:

allow_all_imports: true
apps:
  motion_lights:
    - motion_id: binary_sensor.bevegelsesensor_kjokken
      light_id: light.lys_kjokken
      time_id: input_number.light_timer_5_minutt

`

Has anyone had luck getting autocomplete working for the Jupyter notebook in PyCharm?

Been banging my head against the wall all weekend without much luck. I have it working in the browser, but it makes development so much slower switching over to the browser. I’ll even take a guide on setting up VS Code, I’m very unfamiliar with it, but it atleast supports IntelliJ key bindings. Had no luck with VS Code my first try but it was a fresh install and I had no idea how to set it up.

I’m trying to create a MQTT watchdog in pyscript. It should be simple enough, just post a timestamp on something like watchdog/timestamp and then check it agains dt.timestamp(dt.now())…

Then I thought, maybe also use QOS and check if the message actually gets posted, but when I use mqtt.publish(topic=topic, payload=timestamp,qos=2) I don’t get an error or anything in the return of that function. I understand this is not really a pyscript issue, the strange thing is. If I try the same in the dev-console I do get an error saying it can’t connect to the mqtt broker (also with QOS=0).

So my question is, how do I catch an exception from mqtt.publish?

If the docs are right, that kind of trigger (just a state, without comparison) will not trigger on startup, but whenever the state changes (independent of the value). Can you check the state history? Maybe it gets initialized as β€˜unavailable’ at startup and then the change to β€˜on’ or β€˜off’, once it becomes available, triggers your function.

Anyway, I ask myself why that would trigger unintended light switches, it sounds like a problem in the way you implemented the function itself. Maybe it makes more sense to define separate functions for on and off:

@state_trigger("switch.light_switch=='on'")
def switch_on():
    task.unique("switch_triggered")
    # DO SOMETHING
    pass

@state_trigger("switch.light_switch=='off'")
def switch_off():
    task.unique("switch_triggered")
    # DO SOMETHING
    pass

Like that, always the right state should be kept, even in case of restart (unless there’s something more complicated at work here, which you did not explain).

1 Like

Question. Is there a way using pyscript to manually change an attribute of a sensor. I’m building a β€œto-do” list and I have all the tasks as attributes of a main sensor and would like to change the status attribute to β€œcompleted” when done since when is created is β€œopen”. Thank you.

Hello everyone. I installed Pyscript using Home Assistant Community Store, and when I go to Developer Tools β†’ Services β†’ and type in pyscript, the only services that show up are Reload Pyscript and Start Jupiter Kernel. I’ve created more scripts in my custom_components/pyscripts directory, however they don’t show up in my services. I’ve restarted home assistant, made sure everything is correct in my configuration.yaml file, checked the debug statements, and cannot find what is wrong. Any advice would be great!

From the docs:

Add files with a suffix of .py in the folder <config>/pyscript

I followed the steps to create the example.py file, and tried creating a file of my own. I then called the reload scripts service and restarted home assistant. The new services, such as the services in example.py and the other file still won’t show up. Pretty confused about what is happening.

<config> means the HA config folder, so you should have/create a pyscript folder where your HA configuration.yaml lives, not in custom_component/pyscript.

I’m experiencing the same issue as @davidbd7.

I created two files:

config/pyscript/shopping_list_sync.py 
config/pyscript_modules/write_file.py

I reload pyscript and only see the reload and jupyter service; error log reports:

Exception in </config/pyscript/shopping_list_sync.py> line 8: import write_file ^ ModuleNotFoundError: No module named 'write_file'

I also added write_file.py to the config/pyscript folder and that isn’t recognized either.

Does shopping_list_sync.py (or any other script in config/pyscript) contain this code?

import sys

if "/config/pyscript_modules" not in sys.path:
    sys.path.append("/config/pyscript_modules")

You can alternatively just put write_file.py in <config>/pyscript/modules. See the docs.

Yes, shopping_list_sync.py:

import requests
import sys
import time
from importlib import reload
if "/config/pyscript_modules" not in sys.path:
    sys.path.append("/config/pyscript_modules")

import write_file

write_file = reload(write_file)
...

I tried adding write_file.py to /config/pyscript/modules and now get this error instead:
Exception in </config/pyscript/shopping_list_sync.py> line 10: write_file = reload(write_file) ^ ImportError: module write_file not in sys.modules

I don’t know why you are calling reload() - have you tried removing that?

I removed the reload() and the service shows up, thanks!

Actually didn’t realize I wasn’t on the thread where this script originated, but I now know I’m not too far away from getting the script to work.

I just became aware of that script. It also contains several time.sleep(1) calls, which is a very bad thing since it blocks the entire HASS event loop. Please replace those calls with task.sleep(1).

Please also post on the script thread the fact that the reload() should be removed too.

My HA Configuration.yaml file is in /etc/homeassistant/config and the path for pyscript is /etc/homeassistant/config/custom_components/pyscript. If this is wrong, where should I move the pyscript folder. I appreciate your help!

They should be directly under the Homeassistant root config folder. For example in my case:

root@Openmediavault:/srv/dev-disk-by-uuid-67bfc66a-6dff-432a-8d70-9d2da651d46f/data/docker_data/homeassistant# tree -L 1
.
β”œβ”€β”€ automations.yaml
β”œβ”€β”€ blueprints
β”œβ”€β”€ configuration.yaml
β”œβ”€β”€ core
β”œβ”€β”€ creds.data
β”œβ”€β”€ custom_components
β”œβ”€β”€ dashboard
β”œβ”€β”€ deps
β”œβ”€β”€ gactions
β”œβ”€β”€ google_assistant
β”œβ”€β”€ ha-venv
β”œβ”€β”€ home-assistant.log
β”œβ”€β”€ home-assistant.log.1
β”œβ”€β”€ home-assistant.log.fault
β”œβ”€β”€ html5_push_registrations.conf
β”œβ”€β”€ image
β”œβ”€β”€ integrations
β”œβ”€β”€ known_devices.yaml
β”œβ”€β”€ light_profiles.csv
β”œβ”€β”€ pyscript
β”œβ”€β”€ scenes.yaml
β”œβ”€β”€ scripts.yaml
β”œβ”€β”€ secrets.yaml
β”œβ”€β”€ themes
β”œβ”€β”€ tts
β”œβ”€β”€ watchman_report.txt
β”œβ”€β”€ www
└── zigbee.db