PyLCI code snippets

From ZeroPhone
Jump to: navigation, search

This page contains some useful code snippets you can use in your pyLCI apps.

Minimal pyLCI app structure


menu_name = "Skeleton app"

i = None #Input device
o = None #Output device

def init_app(input, output):
    #Gets called when app is loaded
    global i, o
    i = input; o = output

def callback():
    #Gets called when app is selected from menu

app/ (empty file):


Reading data from a config file that is stored in the app folder

from helpers.config_parse import read_config
config_filename = "config.json"

base_dir = os.path.dirname(sys.modules[__name__].__file__)
config_path = os.path.join(base_dir, config_filename)
config = read_config(config_path)

"read_config" function assumes your config is in JSON format, so you might want to use some other library if you're using some other format.

Restoring config file to defaults if reading it failed

import os,sys
from helpers.config_parse import read_config
current_module_path = os.path.dirname(sys.modules[__name__].__file__)
default_config = '{"your":"default", "config":"to_use"}'
config_path = os.path.join(current_module_path, config_filename)

    config = read_config(config_path)
except (ValueError, IOError):
    print("{}: broken config, restoring with defaults...".format(menu_name))
    with open(config_path, "w") as f:
    config = read_config(config_path)