Что делать если нужно поставить какую-то 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
🌎 Far below the surface, the deep ocean is home to rare animals like the gulper eel, which can expand its mouth wide to swallow prey whole. The giant squid, once considered a sea monster, can reach lengths up to 13 meters and uses long tentacles to catch fish and other deep-sea creatures. ✨
#ocean⚡#animals⚡#deepsea
👉subscribe Interesting Planet
👉more Channels
🌎 Deep below the ocean’s surface, the barreleye fish (Macropinna microstoma) has a transparent, dome-shaped head that lets it look upward through its own skull. Its tubular eyes can pivot inside the head to spot prey above, and the fish lives at depths of 600 to 800 meters off the Pacific coast of North America. ✨
#ocean⚡#animals⚡#deepsea
👉subscribe Interesting Planet
👉more Channels
🌎 In the deep ocean, the frilled shark is one of the rarest living sharks, with an eel-like body and 300 trident-shaped teeth. It lives at depths of 500 to 1,500 meters and was first described in 1884. ✨
#deepsea⚡#animals⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 The vampire squid lives 2,000 to 3,000 meters deep, where sunlight never reaches. It uses filaments to sense drifting food, not for hunting. Despite the name, it doesn’t suck blood—its dark color and cape-like web inspired the name. This rare cephalopod has the largest eyes relative to body size in the animal kingdom. ✨
#ocean⚡#animals⚡#deepsea
👉subscribe Interesting Planet
👉more Channels
🌎 Some deep-ocean animals are so rare that they’re known from only a few specimens. The barreleye fish, for example, has a transparent head and tubular eyes that point upward to spot prey above. It’s found at depths of 600 to 800 meters and can rotate its eyes inside the skull to look forward or up. ✨
#deepsea⚡#animals⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 Far below the ocean’s surface, the dumbo octopus glides using ear-like fins on its head. This rare deep-sea animal lives at depths of 3,000 to 4,000 meters and grows up to 30 centimeters long. ✨
#ocean⚡#animals⚡#deepsea
👉subscribe Interesting Planet
🌎 In the midnight zone over 1,000 meters deep, the comb jelly Bathocyroe fosteri drifts through pitch-black water. Its transparent body is nearly invisible, but rows of cilia beat in waves, scattering light like a rainbow. Researchers first collected specimens near the Bahamas in the 1980s. ✨
#deepsea⚡#animals⚡#biodiversity
👉subscribe Interesting Planet
👉more Channels
🌎 Shrouded in darkness, the “midnight zone” of the ocean lies below 1,000 meters, where sunlight can’t reach and pressure crushes like a dozen elephants. Creatures here glow with bioluminescence and withstand freezing cold, revealing how life adapts to our planet’s most mysterious depths. ✨
#ocean⚡#bioluminescence⚡#deepsea
👉subscribe Interesting Planet
🌎 Vampire squid live more than 2,000 meters below the ocean’s surface, where sunlight never reaches. This deep-sea animal uses long, webbed arms and blue bioluminescent light to confuse predators. Vampire squid can survive with very little oxygen, thriving in one of the planet’s most extreme habitats. ✨
#oceanlife⚡#deepsea⚡#animals
👉subscribe Interesting Planet
👉more Channels
🌎 The barreleye fish, found at depths up to 800 meters, has a transparent head that lets its tubular eyes rotate upward to spot prey. Its eyes can point forward or straight up, helping it see bioluminescent animals in the dark. The barreleye reaches about 15 centimeters in length. ✨
#deepsea⚡#animals⚡#fish
👉subscribe Interesting Planet
👉more Channels
🌎 The fangtooth fish prowls ocean depths over 5,000 meters below the surface. Its oversized teeth are so long they can’t fit in its mouth, forcing the fish’s brain to sit lower in the skull. Despite its fearsome appearance, this deep-sea predator rarely grows longer than 18 centimeters. ✨
#ocean⚡#deepsea⚡#fish
👉subscribe Interesting Planet
🌎 Giant isopods, distant relatives of the common pillbug, inhabit the deep ocean at depths exceeding 500 meters. These armored scavengers can reach up to 50 centimeters in length, surviving on the remains of dead sea animals that sink to the seafloor. ✨
#oceanlife⚡#deepsea⚡#biodiversity
👉subscribe Interesting Planet