How to start using Pyscript

I have installed the PyScript integration with the aim to write more extensive python scripts. So put my first PyScript in the pyscript directory, but HOW can I use it?

It doesn’t show up in the entities (with all the relevant filters on) and I’ve done a PyScript reload. But to no avail; my script can not be called using the ‘call service’.

What is wrong here? Please help!

Post your script. It’s most likely something in the method def.

This is the PyScript:

# json_writer.py

import json

# Define the path and filename for the JSON file
json_file_path = "/config/json_data/data.json"

# Define the JSON data to write to the file
json_data = {
    "key1": "value1",
    "key2": ["value2", "value3"],
    "key3": {
        "nested_key": "nested_value"
    }
}

# Write JSON data to the file
def write_json_to_file(data):
    try:
        with open(json_file_path, "w") as json_file:
            json.dump(data, json_file, indent=4)
        return True
    except Exception as e:
        # Handle any errors
        return False

# Call the function to write JSON data to the file
write_json_to_file(json_data)

Typically a case of RTFM… :flushed: Implementing this example caused the script to show up:

@service
def hello_world(action=None, id=None):
    """hello_world example using pyscript."""
    log.info(f"hello world: got action {action} id {id}")
    if action == "turn_on" and id is not None:
        light.turn_on(entity_id=id, brightness=255)
    elif action == "fire" and id is not None:
        event.fire(id, param1=12, pararm2=80)

Probably the @service does it!

1 Like

Yes, that exposes it to services so you can call it from HA, you can use other defs without @service as internal routines to complete the service calls.

1 Like