Что делать если нужно поставить какую-то 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
Berachain's Infrared Raises $14 Million
Berachain's liquid staking protocol, Infrared, successfully raised $14 million in a Series A token round. The funding aims to support its DeFi initiatives. Read more here: The Block
#DeFi#Berachain#Infrared#Crypto#Investments#Funding#VC
🪐 In 2023, astronomers discovered a free-floating planet called WISEA J110125.95+540052.8, drifting alone about 100 light-years from Earth. Unlike planets tied to stars, rogue planets like this one travel through the galaxy in darkness, warmed only by the faint heat left over from their formation and detectable mainly in infrared light—a reminder that not all worlds need a sun to wander the cosmos. ✨
#rogueplanets⚡#infrared⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The Milky Way may be home to countless rogue planets—worlds that travel alone, not bound to any star. One such loner, called WISEA J083011.95−614123.5, was spotted using infrared telescopes as it drifts in perpetual night, offering a glimpse into what planets look like when cut off from the warmth and light of a sun. ✨
#rogueplanets⚡#infrared⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Astronomers estimate there could be billions of rogue planets—planets not bound to any star—drifting through our galaxy in darkness. One example, PSO J318.5-22, floats alone about 80 light-years from Earth, glowing faintly in infrared because it holds onto leftover heat from its formation, even though it has no sun to warm it. ✨
#rogueplanets⚡#galaxy⚡#infrared⚡#nasa⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The rogue planet PSO J318.5-22, located about 80 light-years away in the constellation Capricornus, drifts alone through space without a star to call home. Unlike planets that orbit a sun, PSO J318.5-22 glows faintly in infrared from the warmth left over from its formation, making it a true cosmic wanderer and one of the few planetary-mass objects visible in the dark between the stars. ✨
#rogueplanets⚡#exoplanets⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The James Webb Space Telescope has revealed distant galaxies like MACS1149-JD1 forming stars much earlier than expected, showing that galaxy building blocks were already in place just 500 million years after the Big Bang. By capturing infrared light, Webb can see through cosmic dust and uncover the birth of some of the universe’s first stars, helping scientists understand how the cosmos evolved from darkness to a landscape filled with galaxies. ✨
#Webb⚡#galaxies⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The James Webb Space Telescope has revealed the most detailed images yet of the galaxy cluster SMACS 0723, showing thousands of galaxies and ancient starlight that traveled over 4.6 billion years to reach us. Webb’s infrared vision lets us peer through dust and see cosmic structures, such as warped arcs of light caused by gravitational lensing—where the cluster’s mass bends and magnifies even more distant galaxies hiding behind it. ✨
#galaxies⚡#infrared⚡#lensing⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The James Webb Space Telescope stunned astronomers by capturing images of the faintest, most distant galaxies ever seen—like GLASS-z13, which formed when the universe was only about 300 million years old. Webb’s infrared eyes pierce cosmic dust, making it possible to observe galaxies and stars that existed just after the Big Bang, revealing clues about how the first stars and galaxies came to life. ✨
#webb⚡#galaxies⚡#infrared⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Near the center of our Milky Way, a cluster of young, massive stars known as the Quintuplet Cluster exists amid clouds of dust, virtually hidden from optical telescopes. Infrared observations have revealed these colossal stars, including the enigmatic "Pistol Star," which burns with a luminosity 1.6 million times brighter than our Sun and sheds mass in powerful, mysterious outbursts. ✨
#QuintupletCluster⚡#PistolStar⚡#infrared
👉subscribe Universe Mysteries
🚀 Infrared to Unlock 27.64 Million Tokens on April 17
Infrared (IR) is set to unlock approximately 27.64 million tokens on April 17 at 0:00 UTC+8. According to ChainCatcher, this information comes from the Web3 asset data platform RootData's token unlocking data. The unlocked tokens are valued at around $1.01 million.
#Infrared#tokenunlocking#Web3#ChainCatcher#RootData#cryptocurrency#April17#digitalassets