Python Interpreter examples¶
Prerequisites: 1 - Calculators (basic objects). Sub-examples 5 and 6 also use 4 - School.
Here you can see how we load and execute Python scripts inside a Sen process.
First make sure that you have the PYTHONPATH environment variable correctly set to point to our
example scripts:
For bash:
For fish:
PYTHONPATH setup: The Python scripts import sen (the Sen Python binding) and optionally generated type modules. Before running these scripts standalone, ensure PYTHONPATH includes the directory containing the sen module and any generated Python packages. When using sen run, Sen automatically extends PYTHONPATH with the paths of Python targets listed in DEPS inside sen_generate_yaml.
Hello Python¶
In this example we just show how to get a Python interpreter running inside a Sen component.
Run it with:
# === hello_python.py ==================================================================================================
# Sen Infrastructure
# Released under the Apache License v2.0 (SPDX-License-Identifier Apache-2.0).
# See the LICENSE.txt file for more information.
# © Airbus SAS, Airbus Helicopters, and Airbus Defence and Space SAU/GmbH/SAS.
# ======================================================================================================================
"""Example module that demonstrates how to use the python component."""
import sen
# this is executed only once (at the start of the component execution)
def run():
"""Sen run: to setup the initial component state."""
print("Python: run")
print(f"Python: the config is: {sen.api.config}")
print(f"Python: the app name is: {sen.api.appName}")
# this is executed every cycle
def update():
"""Sen update: triggers test execution."""
print(f"Python: update (current time: {sen.api.time})")
# this is executed only once (at the end of the component execution)
def stop():
"""Sen stop: trigger that the execution stops."""
print("Python: stop called")
Inspecting objects¶
In this example we can see how to fetch objects coming from other components and print their properties.
Run it with:
This example contains the following files:
# === inspecting_objects.py ============================================================================================
# Sen Infrastructure
# Released under the Apache License v2.0 (SPDX-License-Identifier Apache-2.0).
# See the LICENSE.txt file for more information.
# © Airbus SAS, Airbus Helicopters, and Airbus Defence and Space SAU/GmbH/SAS.
# ======================================================================================================================
"""Example module that demonstrates how to inspect objects."""
import sen
# to store the objects that we want to inspect
list = None
def run():
"""Sen run: to setup the initial component state."""
global list # refer to the global variable defined above # noqa: PLW0603
list = sen.api.open("SELECT * FROM local.kernel") # open it
# register some callbacks to show changes in the list
list.onAdded(lambda obj: print(f"Python: object added {obj}"))
list.onRemoved(lambda obj: print(f"Python: object removed {obj}"))
def update():
"""Sen update: triggers test execution."""
print(f"Python: printing the list at: {sen.api.time})")
print(list)
print("Python: iterating over the objects in the list:")
for obj in list:
print(f"Python: * object {obj.name}")
print(f"Python: - class: {obj.className}")
print(f"Python: - id: {obj.id}")
print(f"Python: - time: {obj.lastCommitTime}")
Creating objects¶
In this example we see how to create and publish objects using Python.
Run it with:
This example contains the following files:
# === creating_objects.py ==============================================================================================
# Sen Infrastructure
# Released under the Apache License v2.0 (SPDX-License-Identifier Apache-2.0).
# See the LICENSE.txt file for more information.
# © Airbus SAS, Airbus Helicopters, and Airbus Defence and Space SAU/GmbH/SAS.
# ======================================================================================================================
"""Example module that demonstrates how to create objects."""
import sen
myObject = testBus = None
def run():
"""Sen run: to setup the initial component state."""
global myObject, testBus # refer to the globals defined above # noqa: PLW0603
type = {
"entityKind": 1,
"domain": 2,
"countryCode": 198,
"category": 1,
"subcategory": 3,
"specific": 0,
"extra": 0,
}
id = {"entityNumber": 1, "federateIdentifier": {"siteID": 1, "applicationID": 1}}
print("Python: creating and publishing the object")
myObject = sen.api.make(
"aircrafts.DummyAircraft", "myAircraft", entityType=type, alternateEntityType=type, entityIdentifier=id
)
testBus = sen.api.getBus("my.tutorial")
testBus.add(myObject)
# setting the speed property to 150
myObject.speed = 150
def update():
"""Sen update: triggers test execution."""
print(myObject)
def stop():
"""Sen stop: trigger that the execution stops."""
global testBus, myObject # refer to the globals defined above # noqa: PLW0603
print("Python: deleting the object")
testBus.remove(myObject)
myObject = None
testBus = None
Interacting with objects¶
Here we can see how to call methods on objects coming from other components.
Run it with:
This example contains the following files:
# === interacting_with_objects.py ======================================================================================
# Sen Infrastructure
# Released under the Apache License v2.0 (SPDX-License-Identifier Apache-2.0).
# See the LICENSE.txt file for more information.
# © Airbus SAS, Airbus Helicopters, and Airbus Defence and Space SAU/GmbH/SAS.
# ======================================================================================================================
"""Example module that demonstrates how to interact with objects."""
import sen
# to store the object
obj = None
def run():
"""Sen run: to setup the initial component state."""
global obj # refer to the global variable defined above # noqa: PLW0603
obj = sen.api.open('SELECT * FROM local.shell WHERE name = "shell_impl"')
def update():
"""Sen update: triggers test execution."""
print("Python: update")
# if the object is present, do something with it
if len(obj) != 0:
print("Python: interacting with the object")
obj[0].info("i16") # print the info of the i16 type
obj[0].ls() # list the current objects in the terminal
obj[0].history() # show the current history
print("Python: asking the process to shut down")
obj[0].shutdown() # trigger the process shutdown
Reacting to events and changes¶
Here we can see how to execute Python code when events are produced or properties change.
It relies on the "school" example to get some activity going.
Run it with:
This example contains the following files:
# === reacting_to_events_and_changes.py ================================================================================
# Sen Infrastructure
# Released under the Apache License v2.0 (SPDX-License-Identifier Apache-2.0).
# See the LICENSE.txt file for more information.
# © Airbus SAS, Airbus Helicopters, and Airbus Defence and Space SAU/GmbH/SAS.
# ======================================================================================================================
"""Example module that demonstrates how to react on events and changes (e.g., object added)."""
import sen
# to store the objects
teachers = None
def teacherDetected(teacher) -> None:
"""Prints information about the detected teacher."""
teacher.onStressLevelPeaked(lambda args: print(f"Python: {teacher.name} stress level peaking to {args}"))
teacher.onStatusChanged(lambda: print(f"Python: {teacher.name} status changed to {teacher.status}"))
def run() -> None:
"""Sen run: to setup the initial component state."""
global teachers # refer to the global variable defined above # noqa: PLW0603
print("Python: run")
# select the object and install some callbacks
teachers = sen.api.open("SELECT school.Teacher FROM school.primary")
teachers.onAdded(teacherDetected)
Using the interpreter from other components¶
Here we publish the interpreter object and can use it from within our shell component.
This example contains the following files:
# $schema: ../base/schema.json
include:
- ../base/shell.yaml
load:
- name: shell
open: [local.py]
- name: py
group: 3
freqHz: 30
bus: local.py
If you open the shell you can use the interpreter with something like this:
The eval function evaluates an expression and returns the result.
The exec function executes statements.
The interpreter holds an internal state, so you can use it in your evaluations.