Что делать если нужно поставить какую-то Python-библиотеку а root-прав нет? То есть в систему библиотеку никак и ничего не поставить.
Есть как минимум два способа это решить правильно!
🔸 Сделать виртуальное окружение и ставить там что угодно.
Это позволит создать полностью независимое исполняемое окружение для ваших приложений.
Все библиотеки будут храниться в домашней директории юзера а значит доступ на запись имеется.
Создать очень просто:
python3 -m venv ~/venvs/myenvname
Теперь активируем окружение
# Linux
source ~/venvs/myenvname/bin/activate
# Windows
%userprofile%\venvs\myenvname\Scripts\activate.bat
Можно ставить любые библиотеки и запускать приложение.
Это стандартный метод работы с любым проектом. Если еще не используете его, то пора начинать. Даже при наличии root доступа!
🔸 Бывает, что нет возможности запустить приложение из своего виртуального окружения. Например, его запускает какой-то сервис от вашего юзера и вставить активацию окружения вы не можете.
В этом случае можно установить библиотеки для Python не глобально в систему, а только для юзера.
Выполните этот код в консоли:
python3 -m site
Вы получите что-то такое:
sys.path = [
'/home/user',
'/usr/lib/python37.zip',
'/usr/lib/python3.7',
'/usr/lib/python3.7/lib-dynload',
'/home/user/.local/lib/python3.7/site-packages',
...
]
USER_BASE: '/home/user/.local'
USER_SITE: '/home/user/.local/lib/python3.7/site-packages'
ENABLE_USER_SITE: True
Нас интересует параметр USER_SITE. Это путь к пользовательским библиотекам, которые доступны по умолчанию, если они есть.
Именно сюда будут устанавливаться модули если добавить флаг --user при установке чего-либо через pip
pip install --user requests
Для этой команды не нужны root-права.
После неё можно запускать системный интерпретатор без виртуальных окружений и установленная библиотека будет доступна для текущего юзера.
Параметр USER_BASE показывает корневую директорию для хранения user-библиотек. Её можно изменить с помощью переменной окружения PYTHONUSERBASE
export PYTHONUSERBASE=~/pylibs
python3 -m site
...
USER_BASE: '/home/user/pylibs'
USER_SITE: '/home/user/pylibs/lib/python3.7/site-packages'
Получается некоторое подобие виртуального окружения для бедных 😁 которое можно менять через эту переменную (не делайте так!Лучше venv!)
🔸 Дописывание пути в PYTHONPATH
Этот способ не входит в список "двух правильных", но тоже рабочий. Здесь придётся сделать всё несколько сложней.
Сначала ставим библиотеку в любое место указывая путь установки
pip3 install -t ~/mylibs modulename
Библиотека установится без привязки к какому-либо интерпретатору. То есть по умолчанию не будет видна. Теперь в нужный момент добавляем этот путь в sys.path или в PYTHONPATH.
Не буду советовать так делать. Единственный раз когда этот способ мне пригодился и решил поставленную задачу, это при создании общей библиотеки для кластера компьютеров.
Модули лежат в сети и подгружаются для всех из одного и того же места. То есть обновлять файлы требуется только один раз а не на всех хосты отдельно.
Минусы такого подхода:
▫️Нужно всем хостам пробить нужный путь в .bashrc или ещё куда-то чтобы он сетапился на старте.
▫️Чем больше хостов тем больше нагрузка на сеть. Иногда такой способ не подходит именно по этой причине. Тогда Ansible вам в помощь.
▫️Не очень подходит если хосты с разными операционками. Некоторые библиотеки различаются для Linux и Windows (там, где есть бинарники) и приходится мудрить более сложные схемы.
#tricks#basic
School holiday adventures await at Parc Glen @ Tengah! Your little ones can bounce on trampolines, explore a cave playground, dig in the sand, or climb through a futuristic looking ant-nest playground. Swipe to the end to plan your best route ➡️
ℹ️#DYK: From January 2026, playgrounds in newly launched BTO projects will be guided by HDB’s new Play Values Framework. Shaped by children and parents’ feedback and with input from early childhood professionals, healthcare professionals and playground specialists, the framework guides the creation of engaging play spaces that support children’s development.
Home buyers, more new homes are coming your way in 2025!
In October, we’ll launch the first BTO project at the former Keppel Club Site. Located next to Berlayer Creek, the project will offer around 1,000 units ranging from 2-room Flexi to 4-room flats, as well as public rental flats, in a central location close to nature. #DYK that a granite rock outcrop, ‘Batu Berlayar’, once stood nearby and was said to have served as a navigational marker for maritime traders? We’ll be sharing more information on the project later this year.
Also, here’s a first look at the Toa Payoh Town (West) BTO project that we’re launching this July. Home buyers will be able to choose from 740 units of 2-room Flexi to 4-room flats, and the project will come with new amenities such as an eating house, shops, and a preschool.
💎#DYK there’s a hidden gem in Jurong West?
Welcome to Jurong West Jewel, thoughtfully designed for residents to live well, live green and live connected.
🔸 Distinctive façade with jewel-shaped motifs
🌳 Fitness stations and playgrounds nestled within lush greenery
👶 Integrated childcare centre, Active Ageing Centre, and Residents’ Network Centre
🚆 Pioneer MRT station and a bus-stop right at your doorstep
🏞️ Leisure spots nearby, including Yunnan Park and Jurong West Stadium and Sports Centre
#DYK The Home ownership Support Team (HST) provides support to rental families who are ready to buy a flat.
Mdm Aliya was one of the rental households who bought a new flat with the support of the HST. With a Step-Up Housing Grant of $15,000 from HDB and her CPF savings, she fully paid off her flat and did not have to take up any mortgage. She’s happy to have a home to call her own. ❤🏠
#DYK The Parenthood Provisional Housing Scheme (PPHS) supports families in need of temporary housing while they await the completion of their new BTO flats?
To meet the demand for PPHS flats, we will double the supply to 4,000 units by 2025.
Find out more about the eligibility criteria and how to apply.
#DYK The HFE letter is a 3-in-1 eligibility assessment that streamlines the flat buying process, informing you upfront of your eligibility to:
1️⃣ Buy a new and/ or resale flat
2️⃣ Receive CPF housing grants, and the amount
3️⃣ Take up an HDB housing loan, and the amount
Remember: You’ll need an HFE letter before you can apply for a flat at the February 2024 Sales Launch. Apply by 15 January 2024 at https://homes.hdb.gov.sg
#DYK that HDB has a 10-year plan to reduce energy consumption in HDB towns by 15%, by 2030? Find out more about the HDB Green Towns Programme: go.gov.sg/hdb-gtp-racetosustainability
If you're thinking of buying a flat at the next sales launch, be sure to apply for an HFE letter early. The HFE letter is valid for 6 months - more on the HFE letter and when you’ll need it in your flat buying journey.
#DYK? You can now apply for housing loans from HDB and participating financial institutions when you apply for an HDB Flat Eligibility (HFE) letter via the HDB Flat Portal: https://homes.hdb.gov.sg
#DYK The Residual Current Circuit Breaker (RCCB) protects you and your family from electric current leakage? Check if your home has one, and follow EMA’s steps to test it today.
PSA to home owners of flats built before 1985 📢 HDB will be assisting eligible HDB homeowners with the installation of an RCCB, if they do not already have one:
▪️For 1- and 2- room flats, the Government will fully fund the cost of the RCCB installation and necessary rewiring
▪️For 3-room and larger flats, the cost will be subsidised by the Government.
#DYK that since 2021, all new HDB estates come with separate chutes for recycling waste?
♻ No need to pre-sort recyclables - sorting is done at the sorting facility
✋ Chutes only open up with a hand lever, instead of a foot pedal, to prevent wet waste from being thrown in
The result? Recyclable waste collected at the pilot project over 1 year was 3 times more than housing estates without recycling chutes!
#DYK? HDB completed close to 50% more flats in 2022 as compared to 2021. The median waiting times for BTO flats currently under construction is 4.3 years. We aim to reduce this to 3 to 4 years from 2024.
Learn more about how we are delivering more homes to Singaporeans.