HABApp: Best practice for installing additional python packages

Hello,

in the documentation it says, that if you want to add python packages, you can do this by creating a docker file, in which you specify the additional packages you need. My HABApp installation is not running in a docker, so I´m wondering how I can/should install python packages needed by my rules.

My current working solution is (example for package googlemaps):

seven@openhab:~ $ cd /usr/share/habapp/
seven@openhab:/usr/share/habapp $ source bin/activate
(habapp) seven@openhab:/usr/share/habapp $ sudo ./bin/python -m pip install googlemaps
(habapp) seven@openhab:/usr/share/habapp $ deactivate

(not sure about the sudo, could be better to use the openhab user or owner of the habapp folder)

This seems to be working. How are you installing additional python packages?

For completeness or if someone wants to do something similar
import logging
import HABApp
from HABApp.openhab.items import NumberItem
import googlemaps


class Traffic(HABApp.Rule):
    def __init__(self):
        super().__init__()

        self.log = logging.getLogger('HABApp.Rules')
        self.gmaps = googlemaps.Client(key='mykey')

        self.run.soon(self.get_duration_from_home_to_work)
        self.run.every_hour(self.get_duration_from_home_to_work)

    def get_duration_from_home_to_work(self):
        result = self.gmaps.distance_matrix('aaa', 'bbb', departure_time='now', mode='driving')

        if result['rows'][0]['elements'][0]['status'] == 'OK':
            time_in_secs = int(result['rows'][0]['elements'][0]['duration_in_traffic']['value'])
            time_in_mins = int(round(time_in_secs / 60, 0))
            self.log.info(f"Driving duration to work: {time_in_mins} min")

            NumberItem.get_item('traffic_duration_to_work').oh_post_update(time_in_mins)


Traffic()

If you look closely this is under the docker section because it’s not immediately clear how do install additional packages when using a docker image.
If you use a virtual environment you already installed a package there (HABApp) which means you already know how to do it. That’s why I didn’t add it to the docs. The only thing to keep in mind is to restart HABApp so it can pick up the additional packages.
Depending on how you set up your folder you should not need to use sudo (and you also don’t need to deactivate).

1 Like

Thanks for your help! I added the restart.

In my case (folder habapp is owned by user openhab) I actually need to use sudo (and chown).

seven@openhab:/usr/share/habapp $ source bin/activate
(habapp) seven@openhab:/usr/share/habapp $ sudo ./bin/python -m pip install somepackage
(habapp) seven@openhab:/usr/share/habapp $ sudo chown -R openhab:openhab .
(habapp) seven@openhab:/usr/share/habapp $ sudo systemctl restart habapp.service

Optional, to leave the venv:

(habapp) seven@openhab:/usr/share/habapp $ deactivate
seven@openhab:/usr/share/habapp $