Что делать если нужно поставить какую-то 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
🌎 Some octopus species, like the mimic octopus, can rapidly change their color and skin texture to blend into diverse backgrounds or imitate venomous sea creatures. This camouflage is controlled by specialized skin cells called chromatophores, iridophores, and leucophores, allowing them to avoid predators or catch prey. ✨
#animals⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 Parrotfish dazzle reefs with scales in neon blues, pinks, and greens, while the stonefish hides perfectly among rocks thanks to its bumpy, mottled skin. Stonefish toxins can cause serious injury if stepped on. ✨
#animals⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 The peacock mantis shrimp stands out for its dazzling rainbow armor and lightning-fast punch. Its eyes detect polarized and multispectral light far beyond human vision. This shrimp's punch can shatter aquarium glass and accelerate as fast as a bullet—up to 23 meters per second. ✨
#animals⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 Few animals rival the peacock mantis shrimp for color and camouflage. Its shell displays vivid blues, reds, and greens, helping it blend with coral while startling predators. The mantis shrimp’s eyes detect polarized light and twelve color channels—far more than humans, who see only three. ✨
#animals⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 Arctic hares survive the icy tundra by changing their fur color—white in winter to blend with snow, brown or gray in summer for camouflage. Adults can leap up to 2 meters in a single bound to escape predators. ✨
#animals⚡#adaptation⚡#camouflage
👉subscribe Interesting Planet
👉more Channels
🌎 Harlequin toads flaunt striking black, yellow, and orange patterns to warn predators of their skin toxins, while the common leaf insect mimics green leaves so closely that even its legs resemble plant veins. Scientists have documented over 3,000 species of leaf-mimicking insects worldwide. ✨
#animals⚡#adaptation⚡#camouflage
👉subscribe Interesting Planet
👉more Channels
🌎 The leafy sea dragon, native to southern Australia, blends perfectly with seaweed thanks to leaf-like extensions on its body. These fins don’t propel it but provide camouflage from predators. Leafy sea dragons reach up to 35 centimeters in length and are closely related to seahorses. ✨
#adaptation⚡#camouflage⚡#ocean
👉subscribe Interesting Planet
👉more Channels
🌎 The orchid mantis of Southeast Asia blends in with flowers thanks to petal-shaped limbs and white, pink, or yellow coloring that matches local orchids. This insect both camouflages from predators and attracts pollinators, which it ambushes for food. ✨
#animals⚡#camouflage⚡#insects
👉subscribe Interesting Planet
👉more Channels
🌎 The Indian leaf butterfly disguises itself as a dead leaf when at rest, with veins and brown patterns mimicking real foliage. When disturbed, it reveals bright blue and orange wings underneath—stunning colors that help startle predators. This butterfly is native to forests in South and Southeast Asia. ✨
#camouflage⚡#adaptation⚡#insects
👉subscribe Interesting Planet
👉more Channels
🌎 The mimicry leaf insect looks exactly like a real leaf, down to brown spots that resemble decay. This remarkable disguise protects it from hungry predators by blending perfectly into the forest floor. ✨
#insects⚡#camouflage⚡#adaptation
👉subscribe Interesting Planet
🌎 Peacock spiders from Australia show off bold, iridescent colors during their unique courtship dances. Males raise flaps on their abdomen that resemble tiny rainbows to attract females. Over 80 species have been identified, each with distinct colors and patterns. ✨
#animals⚡#camouflage⚡#spiders
👉subscribe Interesting Planet
🌎 In Madagascar, the leaf-tailed gecko uses its flattened body and jagged skin edges to blend perfectly with tree bark, becoming nearly invisible to predators. This camouflage is so advanced that even experienced biologists often miss spotting them during the day. ✨
#reptiles⚡#camouflage⚡#Madagascar
👉subscribe Interesting Planet