Что делать если нужно поставить какую-то 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
🌎 Trapped in an Andes avalanche in 1972, survivors of a plane crash endured 72 days in freezing mountains, rationing food and melting snow for water—proving human resilience in the harshest conditions. ✨
#survival⚡#history⚡#resilience
👉subscribe Interesting Planet
🌎 The Resurrection Fern can survive months or years without rain by curling up and looking dead. With just a splash of water, it springs back to vibrant green life, showcasing an extraordinary natural survival trick for drought-prone environments. ✨
#plants⚡#adaptation⚡#resilience
👉subscribe Interesting Planet
🌍 Some coral reefs in the Red Sea host unique fish and coral species that can tolerate extreme heat and high salt levels, making them among the most resilient reef ecosystems on Earth. ✨
#coral⚡#marine⚡#resilience⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Ad Al-Wafa, a Gaza, questa settimana si è celebrata la cerimonia di fine anno scolastico per migliaia di bambini.
Un evento che in condizioni normali sarebbe stato occasione di festa ma che si è trasformato in un momento intriso di dolore. I volti dei piccoli brillavano d’orgoglio mentre ricevevano i diplomi ma dietro ai sorrisi si nascondeva un vuoto profondo: nessun genitore ad applaudirli, nessuno a scattare foto o a sussurrare parole di incoraggiamento.
Un rapporto dell’ONU rivela che oltre il 90 % delle scuole e università sono state danneggiate o distrutte, privando dell’istruzione più di 800.000 bambini e ragazzi e interrompendo la vita accademica di circa 90.000 universitari. Oggi tutti questi ragazzi studiano in tende di fortuna gestire da Unicef, ONU E UNRWA continuamente bersagliate dall’artiglieria di Israele.
#gazagenocide#gazastudents#resilience
🌎 Trapped under debris for 17 days after a 2015 Nepal earthquake, Pemba Tamang survived by drinking muddy water dripping from rubble and eating small snacks. He emerged with only minor injuries after nearly 2½ weeks underground, making it one of the longest earthquake survival cases recorded. ✨
#survival⚡#earthquake⚡#resilience
👉subscribe Interesting Planet
👉more Channels
🌎 The tardigrade’s cousin, the rotifer, can survive drying out for decades by entering a state called cryptobiosis. When water returns, it wakes up as if nothing happened, showing remarkable resilience in the micro-world. ✨
#rotifer⚡#cryptobiosis⚡#resilience
👉subscribe Interesting Planet
As the 60-day ceasefire deadline ended, the people of southern #Lebanon returned to their homes despite Israeli violence. 15 martyrs and 83 injured in the ongoing struggle for their land.
#DayOfReturn#CeasefireDeadline#Resilience#Israel#SouthernLebanon#Occupation
After over a year of displacement, the people of southern #Lebanon return—not to homes, but to the land scarred by Israeli aggression. Their spirit is unbroken.
#Resilience#SouthernLebanon#ReclaimingHome#Rebuilding#Israel#LebaneseArmy
🚀 South Korea's Central Bank Governor: Export Performance Exceeds Expectations
South Korea's central bank governor, Lee Chang-yong, has stated that the country's export performance has surpassed expectations. According to Jin10, Lee highlighted the positive export figures during a recent address, noting that the results are better than initially anticipated. This development comes amid ongoing global economic challenges, where South Korea's export sector has shown resilience and adaptability. The improved export performance is seen as a crucial factor in supporting the nation's economic stability and growth. Lee's remarks underscore the importance of exports in South Korea's economic strategy, as the country continues to navigate complex international trade dynamics.
#SouthKorea#CentralBank#ExportPerformance#EconomicGrowth#GlobalEconomy#Resilience#TradeDynamics#LeeChangYong#EconomicStability
When kids have big emotions, we tend to think they are being overly sensitive, that they need more resilience. Most of the time it is because there is a lot happening for the child that we can't see and don't know, that is pushing them beyond their means of coping. Instead we can change the response from they are overreacting, to seeing a child who has a lot happen for them, they are doing the best they can. They need our help not judgement.
#parenting#positiveparenting#gentleparenting#resilience#respectfulparenting#psychologist#play#playtherapy#childdevelopment#childtherapy#parentingtips#teachers#asd#family#life#adhd#mumlife#momlife#dads#consciousparenting
https://www.instagram.com/p/Ctd93W8vEM9/