- K210.ORG
- Исходные данные
- Обновление Python
- Переустановка Home Assistant
- Upgrading Your Home Assistant Core Python Virtual Environment
- Step 1: Install new version of Python
- Step 2: Backup your current Python packages
- Step 3: Remove old Python virtual environment and create a new one
- Step 4: Install packages and Home Assistant into Python virtual environment
- Final thoughts
- Installing Home Assistant Core in a python virtual environment
- Setting Dependencies
- Installing Home Assistant
- Manual start
- Automatic start
- Update
K210.ORG
Если вы пользуетесь Home Assistant, то после очередного обновления могли заметить на появившееся уведомление о том, что «Support for the running Python version 3.7.3 is deprecated and will be removed in the first release after December 7, 2020. Please upgrade Python to 3.8.0 or higher».
В стандартных системных репозиториях обычно содержатся стабильные и надежные версии пакетов, а не самые свежие и актуальные. И по состоянию на середину января 2021 года Python в репозиториях Debian и Ubuntu так и не спешат обновлять до версии 3.8.x.
Поэтому единственный вариант убрать назойливое уведомление и избавить себя от возможных проблем с совместимостью грядущих обновлений Home Assistant — это установить новую версию Python вручную, предварительно собрав ее из исходников.
Исходные данные
В этой статье я буду исходить из того, что:
- У вас уже установлен Home Assistant
- Он установлен в виртуальное окружение Python
- Используется операционнная система на базе Debian или Ubuntu
Если вы пользуетесь Docker-контейнерами или дистрибутивом Hass.io, то обновлять пакеты вручную вам не придется.
Обновление Python
Процесс обновления описан на примере актуальной на момент написания статьи версии Python 3.9.1. На странице загрузок Python всегда можно посмотреть номер свежего релиза и заменить ссылки на скачивание и распаковку архива в приведенных ниже командах.
Для начала остановим Home Assistant:
sudo systemctl stop home-assistant@homeassistant.service
Установим нужные для сборки из исходников пакеты:
sudo apt-get install build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libxslt-dev libxml2-dev libjpeg-dev zlib1g-dev
Скачаем и распакуем архив с Python 3.9.1:
wget https://www.python.org/ftp/python/3.9.1/Python-3.9.1.tgz tar xzvf Python-3.9.1.tgz cd Python-3.9.1
Соберем его из исходников и запустим установку:
./configure --enable-optimizations make -j 4 sudo make install
Процесс сборки занимает около 12 минут на Raspberry Pi 4, поэтому придется запастись терпением.
После завершения установки можно проверить, что Python действительно обновился путем выполнения двух команд:
python3 --version pip3 --version
И если в консоли появится такие ответы, то процесс обновления прошел успешно:
Теперь обновим менеджер пакетов pip:
sudo /srv/homeassistant/bin/python3.9 -m pip install --upgrade pip sudo python3.9 -m pip install --upgrade pip
В случае если после обновления Python при запуске Home Assistant появится ошибка с доступностью библиотеки libffi.so.7 можно создать симлинк с libffi.so.7 на нее:
sudo ln -s /usr/lib/arm-linux-gnueabihf/libffi.so.6 /usr/lib/arm-linux-gnueabihf/libffi.so.7
Если симлинк не создается, то значит в вашей системе libffi.so.6 находится по другому пути. Найдите корректный путь через поиск по названиям файлов:
find /usr/lib -name "libffi.so*"
Переустановка Home Assistant
Теперь переустановим Home Assistant. Для этого сохраним в файл список используемых им пакетов Python:
cd /home/homeassistant/ sudo -u homeassistant -H -s source /srv/homeassistant/bin/activate pip3 freeze –local > requirements.txt deactivate exit
Удалим директорию с установленным Home Assistant и создадим ее заново:
sudo rm -r /srv/homeassistant sudo mkdir /srv/homeassistant sudo chown homeassistant:homeassistant /srv/homeassistant
Запустим процесс установки по сохраненному ранее списку пакетов:
sudo -u homeassistant -H -s cd /srv/homeassistant python3.9 -m venv . source /srv/homeassistant/bin/activate pip3 install wheel pip3 install -r /home/homeassistant/requirements.txt
И, наконец, перезапустим сервис Home Assistant:
sudo systemctl restart home-assistant@homeassistant
На этом процесс обновления завершен окончательно, и после перезапуска из панели уведомлений должно исчезнуть сообщение о неподдерживаемой версии Python.
Upgrading Your Home Assistant Core Python Virtual Environment
Since Python 3.9 is available, Home Assistant announced they were going no longer support Python versions lower than 3.8. This happens from time to time. If you run Home Assistant Core in a Python virtual environment, then you need to take action to maintain compatibility. I always forget these steps, so I decided to write an article I could always refer to.
Step 1: Install new version of Python
The first step is to install the new version of Python. How you do this will depend on what OS you are running. Many are woefully behind in their default Python versions. I run Ubuntu, and all my commands will be with Ubuntu in mind, but are easily adaptable to other distros. You check your version of Python by running the following commands:
python --version python3 --version
You’ll probably be running an older version of Python than you want. You can check your repos to see if there is an up to date version. If so, you can install it directly from the repos. Otherwise, Python is pretty easy to compile and install from source. If you wanted to install Python 3.8.5 you would do the following:
wget https://www.python.org/ftp/python/3.8.5/Python-3.8.5.tgz tar -xzf Python-3.8.5 cd Python-3.8.5 ./configure make -j 4 sudo make install
Depending on the speed of your system, this could take a little time, but should be straight forward.
Step 2: Backup your current Python packages
I don’t know if this step is strictly necessary to upgrading your Python virtual environment, but it is certainly prudent, especially if you made some changes and customization to Home Assistant that involved Python packages (like custom components). Assuming your Home Assistant config is in /home/homeassistant/.homeassistant and your Python virtual environment is in /srv/homeassistant:
cd /home/homeassistant/.homeassistant sudo -u homeassistant -H -s source /srv/homeassistant/bin/activate pip3 freeze –local > requirements.txt
This will put a listing of all your python packages in the file requirements.txt. You might want to take a peek at the file to make sure it looks right.
Step 3: Remove old Python virtual environment and create a new one
The first time I did this it was the scariest part. Instead of deleting the old python virtual environment, I recommend moving/renaming it, just in case. I recommend you stop Home Assistant at this point as well, although I don’t know that it is required:
sudo systemctl stop [email protected] cd /srv/ sudo mv homeassistant homeassistantold sudo mkdir homeassistant sudo chown homeassistant:homeassistant homeassistant sudo -u homeassistant -H -s cd /srv/homeassistant python3.8 -m venv .
Step 4: Install packages and Home Assistant into Python virtual environment
You are almost done. This is possibly an optional step, but a couple of times in the past I’ve needed to install python packages when I haven’t done this. Use the requirements.txt file you created earlier to reinstall all the packages you had installed in the previous virtual environment.
source /srv/homeassistant/bin/activate cd /home/homeassistant/.homeassistant pip3 install -r requirements.txt
Installing the packages might take a while and you may see some errors or failures, but generally, you don’t have to worry about them (I didn’t and things have always worked fine). Now install and start Home Assistant:
Final thoughts
That’s it. Hopefully, it all goes well. It has for me the couple of times I’ve had to do it. If you’ve decided to run Home Assistant Core in a Python virtual environment you’ll probably have to do this procedure about once a year.
Interested in supporting HomeTechHacker?
Have you found the content on this site useful? If so, are you interested in supporting me and this site? There’s no obligation of course, but I would really appreciate any support you can give. Below are a few ways you can show support:
- Share this site with your friends and on social media (use the sharing links at the end of this page for your convenience)
- Subscribe to this site
- Purchase one of my books, The Personal Cybersecurity Manual, The Home Network Manual or The Smart Home Manual, for yourself or as a gift
- Put a link to HomeTechHacker on a site you have access to. Be sure to let me know about it!
- Reach out to me via my contact page or Twitter and let me know something I should write about
- Shop at Amazon through my affiliate links and ads on these pages. See my disclosures for more details about affiliate links. You can also just shop from one of the links below:
- HomeTechHacker Shop: This is a listing of products that I use, have reviewed, and that I recommend
- HomeTechHacker Technology Advisor: This suite of tools will give you customized home technology product recommendations based on your needs
- My Amazon affiliate link: Just click on this link to go to Amazon and shop
Thank you! I really appreciate it!
Installing Home Assistant Core in a python virtual environment
This method can only be used on the operating system Armbian Linux by JetHome.
When using this method of installation it is not possible to work with аддонами.
Setting Dependencies
Starting with Home Assistant Core version 2022.* you need to use python version at least 3.9.
Check the version of python3 installed on your system:
If using python version 3.8 or lower, python version 3.9 or higher is required beforehand.
sudo apt install python3-dev python3-pip python3-venv python3-sqlalchemy libffi-dev build-essential cargo
Install additional packages:
sudo apt update sudo apt install python3-dev python3-pip python3-venv python3-sqlalchemy libffi-dev build-essential cargo
Installing Home Assistant
Below is an example of how to install Home Assistant Core in the current user’s home directory.
The Home Assistant working directory, where the configuration file and log files are stored, in this case will be ~/.homeassistant .
To install, run the following commands:
If the python3 version is smaller than 3.9 then the virtual environment must be created with the additionally installed python3.9:
python3.9 -m venv homeassistant
cd ~ python3 -m venv homeassistant cd homeassistant source bin/activate python3 -m pip install wheel pip3 install homeassistant
Manual start
To start Home Assistant, run the command (without leaving the virtual environment):
It takes a long time to install and run Home Assistant for the first time.
After a while, you will be able to connect to the system via a browser at http://localhost:8123.
Automatic start
1. Для автоматического запуска Home Assistant при загрузке системы необходимо создать файл /etc/systemd/system/home-assistant@$USER.service (где $USER — логин, под которым был установлен Home Assistant):
sudo nano /etc/systemd/system/home-assistant@$USER.service
[Unit] Description=Home Assistant After=network-online.target [Service] Type=simple User=%i WorkingDirectory=/home/%i/.homeassistant ExecStart=/home/%i/homeassistant/bin/hass -c "/home/%i/.homeassistant" [Install] WantedBy=multi-user.target
sudo systemctl enable home-assistant@$USER.service
sudo systemctl start home-assistant@$USER.service
Update
sudo systemctl stop home-assistant@$USER.service
cd ~/homeassistant source bin/activate
pip3 install --upgrade homeassistant
deactivate sudo systemctl start home-assistant@$USER.service
© Copyright 2023, JetHome. Last updated on 27.01.2023 08:11:07 UTC.