Что делать если нужно поставить какую-то 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
Planning to make full use of the Vaccinated Travel Lanes this holiday season, or heading for a staycation?
Don’t forget to go through the ‘Check and Protect’ checklist for a thorough #MozzieWipeout of your home before you head off! https://go.gov.sg/dengue-checklist
Sudden rain showers are common in Singapore, so if you leave your pails or plant pots where they can collect water, do pay extra attention and drain these containers if they have collected any water.
Here’s a checklist for a thorough #MozzieWipeout: https://go.gov.sg/dengue-checklist
Have you emptied out your flower pot plates after watering your plants today? These plates tend to collect water, and can become mosquito breeding habitats if left unattended. Be sure to add emptying out the flower pot plates to your “To-do List” after watering your plants! Here’s a checklist for a thorough #MozzieWipeout: https://go.gov.sg/dengue-checklist
The annual National Dengue Prevention Campaign was launched today, to rally everyone to take urgent action to prevent mosquito breeding and a possible surge in dengue cases, amidst the continued high Aedes aegypti mosquito population, and higher circulation of less common Dengue virus serotypes.
The fight against dengue involves all of us. Let’s step up dengue prevention by doing the #MozzieWipeout regularly. go.gov.sg/mozzieproof
Planning a staycation with your SingapoRediscover vouchers? Keep yourself and your loved ones safe by going through the ‘Check and Protect’ checklist for a thorough #MozzieWipeout before your stay! https://go.gov.sg/dengue-checklist
Staying home during this COVID-19 period has brought out the green thumb in many of us. And yet, with interest comes responsibility, too! Set a daily reminder to keep your plants nourished and your home protected from dengue too: https://go.gov.sg/dengue-checklist#MozzieWipeout
The gully traps in our homes are perfect for mosquito multiplication! Cover rarely used gully traps or install anti-mosquito valves, to prevent mosquito breeding. Here’s a ‘Check and Protect’ checklist for your thorough #MozzieWipeout today: https://go.gov.sg/dengue-checklist
Do you know where are the favourite places for mosquitoes to lay their eggs?
Pails, flower pot plates/trays and ornamental vases are some of the persistent mosquito breeding habitats in homes. It’s time to search for and destroy these breeding habitats! If you’re not sure how, get started here: https://go.gov.sg/dengue-checklist#MozzieWipeout
The number of weekly dengue cases has declined by more than 50% from its peak this year. However, a 12% increase in the Aedes aegypti mosquito population was detected in the last 3 weeks.
So let’s not let our guard down; continue doing the #MozzieWipeout at least once a week and taking protective actions (go.gov.sg/stopdenguenow). You can also get regular alerts on areas with higher Aedes mosquito population and dengue clusters on myENV app (www.nea.gov.sg/myENV) with this step-by-step guide!
Think it’s impossible for mosquito eggs to hatch in your dish tray, mere inches away from your cups and plates? It certainly isn’t. All mosquitoes need is a 20 cent-sized drop of water to breed. Time to do a thorough check in your house! #MozzieWipeouthttps://go.gov.sg/dengue-checklist
Besides doing the #MozzieWipeout, take these 3 simple actions to protect yourself and your loved ones, especially if you live in a dengue cluster area: Spray, Apply, Wear. More tips here: www.nea.gov.sg/stop-dengue