- Saved searches
- Use saved searches to filter your results more quickly
- License
- custom-components/pyscript
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Python Scripts
- Writing your first script, reading input and logging the activity
- Triggering events
- Calling Services
- Documenting your Python scripts
- Services
- Service python_script.reload
- Help us to improve our documentation
- Categories
- On this page
- Pyscript: Python Scripting for Home Assistant¶
- Contents¶
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Pyscript adds rich Python scripting to HASS
License
custom-components/pyscript
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
see #473. This is a hack; should re-implement using RestoreEntity.
Git stats
Files
Failed to load latest commit information.
README.md
Pyscript: Python Scripting for Home Assistant
This HACS custom integration allows you to write Python functions and scripts that can implement a wide range of automation, logic and triggers. State variables are bound to Python variables and services are callable as Python functions, so it’s easy and concise to implement logic.
Functions you write can be configured to be called as a service or run upon time, state-change or event triggers. Functions can also call any service, fire events and set state variables. Functions can sleep or wait for additional changes in state variables or events, without slowing or affecting other operations. You can think of these functions as small programs that run in parallel, independently of each other, and they could be active for extended periods of time.
Pyscript also provides a kernel that interfaces with the Jupyter front-ends (eg, notebook, console, lab and VSCode). That allows you to develop and test pyscript code interactively. Plus you can interact with much of HASS by looking at state variables, calling services etc.
For more information about the Jupyter kernel, see the README. There is also a Jupyter notebook tutorial, which can be downloaded and run interactively in Jupyter notebook connected to your live HASS with pyscript.
Under HACS -> Integrations, select «+», search for pyscript and install it.
From the latest release download the zip file hass-custom-pyscript.zip
cd YOUR_HASS_CONFIG_DIRECTORY # same place as configuration.yaml mkdir -p custom_components/pyscript cd custom_components/pyscript unzip hass-custom-pyscript.zip
Alternatively, you can install the current GitHub master version by cloning and copying:
mkdir SOME_LOCAL_WORKSPACE cd SOME_LOCAL_WORKSPACE git clone https://github.com/custom-components/pyscript.git mkdir -p YOUR_HASS_CONFIG_DIRECTORY/custom_components cp -pr pyscript/custom_components/pyscript YOUR_HASS_CONFIG_DIRECTORY/custom_components
Installing the Pyscript Jupyter kernel is optional. The steps to install and use it are in this README.
- Go to the Integrations menu in the Home Assistant Configuration UI and add Pyscript Python scripting from there. Alternatively, add pyscript: to /configuration.yaml ; pyscript has two optional configuration parameters that allow any python package to be imported if set and to expose hass as a variable; both default to false :
pyscript: allow_all_imports: true hass_is_global: true
Contributions are welcome! You are encouraged to submit PRs, bug reports, feature requests or add to the Wiki with examples and tutorials. It would be fun to hear about unique and clever applications you develop. Please see this README for setting up a development environment and running tests.
Even if you aren’t a developer, please participate in our discussions community. Helping other users is another great way to contribute to pyscript!
- Documentation stable: latest release
- Documentation latest: current master in Github
- Discussion and help
- Issues
- Wiki
- GitHub repository (please add a star if you like pyscript!)
- Release notes
- Jupyter notebook tutorial
Copyright (c) 2020-2023 Craig Barratt. May be freely used and copied according to the terms of the Apache 2.0 License.
About
Pyscript adds rich Python scripting to HASS
Python Scripts
This integration allows you to write Python scripts that are exposed as services in Home Assistant. Each Python file created in the /python_scripts/ folder will be exposed as a service. The content is not cached so you can easily develop: edit file, save changes, call service. The scripts are run in a sandboxed environment. The following variables are available in the sandbox:
Name | Description |
---|---|
hass | The Home Assistant object. Access is only allowed to call services, set/remove states and fire events. API reference |
data | The data passed to the Python Script service call. |
logger | A logger to allow you to log messages: logger.info() , logger.warning() , logger.error() . API reference |
time | The stdlib time available as limited access. |
datetime | The stdlib datetime available as limited access. |
dt_util | The homeassistant.util.dt module. |
Other imports like min , max are available as builtins. See the python_script source code for up-to-date information on the available objects inside the script.
It is not possible to use Python imports with this integration. If you want to do more advanced scripts, you can take a look at AppDaemon or pyscript
Writing your first script, reading input and logging the activity
This is a simplified example that does no real work. It is created as a first step, to help with:
- Demonstrating how to setup the script
- How to process the input data
- How to log the script activity
- How to troubleshoot / manually call the script.
Start by enabling the Python Scripts integration and create the first script.
- Add to configuration.yaml : python_script:
- Create the folder /python_scripts
- Create a file /python_scripts/hello_world.py in the folder and give it this content:
# `data` is available as builtin and is a dictionary with the input data. name = data.get("name", "world") # `logger` and `time` are available as builtin without the need of explicit import. logger.info("Hello <> at <>".format(name, time.time()))
- Start Home Assistant to reload the script configuration.
- Call your new python_script.hello_world service (with parameters) from the Services, using the YAML mode.
service: python_script.hello_world data: name: "Input-Text"
Running this script show absolutely no output on the screen, but it logs with level info . You must have the Logger enabled at least for level info .
Your configuration.yaml should include something like this.
Triggering events
The following example shows how to trigger a custom event over the hass.bus .
This example uses the hello_world.py from the previous example. Edit the file adding the code listed below to the end of the file. There is no need to reload the configuration or restart Home Assistant.
hass.bus.fire("hello_world_event", "wow": "from a Python script!">)
This script doesn’t output anything. However, you can view the events being fired in the Developer tools.
From a separate browser window or tab, go to Developer Tools -> Events and at Listen to events type hello_world_event and then press Start listening . You should see something like this:
event_type: hello_world_event data: wow: from a Python script! origin: LOCAL time_fired: "2022-09-19T16:15:39.613378+00:00" context: id: 01GDB8H9JXJ1N23Q62SHX6PTBK parent_id: null user_id: null
Calling Services
The following example shows how to call a service from python_script . This script takes two parameters: entity_id (required), rgb_color (optional) and calls light.turn_on service by setting the brightness value to 255 .
# turn_on_light.py entity_id = data.get("entity_id") rgb_color = data.get("rgb_color", [255, 255, 255]) if entity_id is not None: service_data = "entity_id": entity_id, "rgb_color": rgb_color, "brightness": 255> hass.services.call("light", "turn_on", service_data, False)
The above python_script can be called using the following YAML as an input.
- service: python_script.turn_on_light target: entity_id: light.bedroom data: rgb_color: [255, 0, 0]
Documenting your Python scripts
You can add names and descriptions for your Python scripts that will be shown in the frontend. To do so, simply create a services.yaml file in your /python_scripts folder. Using the above Python script as an example, the services.yaml file would look like:
# services.yaml turn_on_light: name: Turn on light description: Turn on a specific light and set its color. fields: entity_id: description: The light that will be turned on. example: light.bedroom rgb_color: description: The color to which the light will be set. example: [255, 0, 0]
For more examples, visit the Scripts section in our forum.
Services
Available services: reload .
Service python_script.reload
Reload all available python_scripts from the /python_scripts folder, as a quicker alternative to restarting Home Assistant.
Use this when creating a new Python script, or after updating the /python_scripts/services.yaml file.
You don’t have to call this service when you change an existing Python script.
This service takes no service data attributes.
Help us to improve our documentation
The Python Scripts integration was introduced in Home Assistant 0.47, and it’s used by 3% of the active installations. It scores internal on our quality scale.
Categories
On this page
Pyscript: Python Scripting for Home Assistant¶
This HACS custom integration for Home Assistant allows you to write Python functions and scripts that can implement a wide range of automation, logic and triggers. State variables are bound to Python variables and services are callable as Python functions, so it’s easy and concise to implement logic.
Contents¶
- Overview
- Installation
- Option 1: HACS
- Option 2: Manual
- Install Jupyter Kernel
- Jupyter Tutorial
- Writing your first script
- An example using triggers
- Configuration
- Reloading Scripts
- State Variables
- Calling services
- Firing events
- Function Trigger Decorators
- @state_trigger
- @time_trigger
- @event_trigger
- @mqtt_trigger
- @state_active
- @time_active
- @pyscript_compile
- @pyscript_executor
- @service(service_name, …)
- @task_unique
- State variables
- Service Calls
- Event Firing
- Logging
- Tasks
- Global Context
- Workflow
- Importing
- Trigger Closures
- Accessing YAML Configuration
- Access to Hass
- Avoiding Event Loop I/O
- Persistent State
- Language Limitations
© Copyright 2020-2023, Craig Barratt Revision d0b4d882 .
Versions latest stable 1.4.0 1.3.3 1.3.2 1.3.1 1.3.0 1.2.1 1.2.0 Downloads pdf html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.