Что делать если нужно поставить какую-то 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
A female Aedes mosquito gets infected with the Dengue virus when it bites a person infected with dengue. It then transmits dengue to other healthy individuals it goes on to bite.
Help to break the dengue transmission cycle!
✅ Everyone should use insect repellent and carry out other S-A-W actions to protect themselves from being bitten by mosquitoes.
✅ Those diagnosed with or suspected to be infected with dengue are also advised to avoid further mosquito bites, to prevent passing on the Dengue virus to mosquitoes and other people in their neighbourhoods.
S-A-W:
✅ Spray insecticide in dark corners around the house
✅ Apply insect repellent regularly
✅ Wear long-sleeve tops and long pants
📱 Download the myENV app to receive alerts on high Aedes mosquito populations near you, or visit go.gov.sg/dengue-high-risk
#DenguePrevention
Heading out for holiday adventures? Before you dash, don’t give the mozzies any room to stay!
Follow the B-L-O-C-K steps and mozzie-proof your home before you roam:
✅ Break up hardened soil
✅ Lift and empty flowerpot plates
✅ Overturn pails and wipe their rims
✅ Change water in vases
✅ Keep roof gutters clear and place BTI insecticide
Let’s make this holiday season not only merry but also mindful.
#BLOCKDengue#DenguePrevention
Going on your festive holiday escapade? 🏖
Give the mozzies no room to stay! Follow the B-L-O-C-K steps and mozzie-proof your home before you roam:
✅ Break up hardened soil
✅ Lift and empty flowerpot plates
✅ Overturn pails and wipe their rims
✅ Change water in vases
✅ Keep roof gutters clear and place BTI insecticide
Together, we can keep dengue at bay. Learn more: https://go.gov.sg/mozzieproof
#BLOCKDengue#DenguePrevention
#SGDengueUpdate The number of active dengue clusters reported continues to remain high, with 64 active clusters reported as of 28 Dec. 198 dengue cases were reported in the week ending 26 Dec, and the cumulative number of dengue cases for this year stands at more than 35,100.
Let’s keep up our #DenguePrevention efforts and continue doing the #MozzieWipeout at least once a week. Find out what else you can do to protect yourself and your family at go.gov.sg/mozzieproof
#SGDengueUpdate As of 17 Dec 2020, there have been 34,844 reported dengue cases this year, with 228 cases reported last week. While NEA has closed about 98% of the dengue clusters notified since the beginning of 2020, there are still over 230 residential areas with high Aedes aegypti mosquito population currently.
So let’s stay vigilant and keep up our #DenguePrevention efforts. If you’re planning to go for a staycation, don’t forget to do the #MozzieWipeout first! Learn more: go.gov.sg/mozzieproof
🦟They’re small, they’re pesky, and they’re definitely not welcome! Mosquitoes love stagnant water - don’t let them crash the party.
It’s time for a Real-World Quest! Carry out the #BLOCKdengue steps at least once a week and mozzie-proof your home:
✅ Break up hardened soil
✅ Lift and empty flowerpot plates
✅ Overturn pails and wipe their rims
✅ Change water in vases
✅ Keep roof gutters clear and place BTI insecticide
#DenguePrevention#Minecraft
Don't let your home become the Upside Down for mozzies! 🦟
The #BLOCKdengue steps are your weekly defence against these tiny monsters. Do these at least once a week:
✅ Break up hardened soil
✅ Lift and empty flowerpot plates
✅ Overturn pails and wipe their rims
✅ Change water in vases
✅ Keep roof gutters clear and add BTI insecticide
#DenguePrevention#StrangerThings