Что делать если нужно поставить какую-то 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
Here at DWF Labs, we are committed to supporting our portfolio companies through thick and thin 🤝🏽
We were saddened to hear about the recent security breach at Gala Games, which led to unauthorised transactions involving $GALA tokens.
In response to this incident, we have taken proactive steps to alleviate market selling pressures and have purchased 28 million $GALA tokens on the open market. This aims to stabilise the token's value and express our unwavering support during these challenging times.
The security of our investments and their communities is important to us.
From their latest update, the Gala Games team has confirmed that the issue has been contained and they are securing all contracts and implementing enhanced safeguards to prevent future occurrences.
We are confident in Gala Games' ability to navigate this setback and emerge stronger 🔥
There will always be ups and downs in crypto but we will be #StrongerTogether.
Let's go Gala Games!🥊💥
THANK YOU to everyone who tuned in our call today!!! Amazing guest speaker, amazing questions and answers!!!
We look forward to bringing more guest speakers who are passionate about education, inspiring others to pursue their dreams, and encouraging YOU to do the same!!
NEVER, EVER GIVE UP!!! 💪🏼🔥
We are #strongertogether.
🇺🇿❤️🤝🇺🇸
https://t.me/AmericanEDU
🔍 UK Plans to Train 30k Ukrainian Troops by Year End 🔥
🔫 British Defense Minister, Grant Shapps, revealed the ambitious goal in an interview with Sky News.💂♂️
🌐 "By the end of this year, our aim is to prepare 30k Ukrainian soldiers," Shapps declared.🇬🇧🤝🇺🇦
💪 London's determination to support Kyiv remains unwavering. "We stand shoulder to shoulder with the Ukrainians," he emphasized.💪
🎯 Previously, over 20k Ukrainian soldiers received training on British military grounds.📚
💥 The US identified this effort as one of the greatest threats to the Ukrainian Armed Forces.💥
#UKSupportsUkraine🇬🇧🤝🇺🇦#StrongerTogether💪
https://dcweekly.org/2023/09/24/britain-to-train-30000-ukrainian-soldiers-by-year-end-solidifying-support-amidst-tensions/
Subscribe to @BadVolfNews
Happy Independence Day, Nigeria! 🇳🇬
As we celebrate 64 years of independence, the NCDC remains committed to prioritising and protecting the health of every Nigerian
Let us continue to work towards a future free from disease outbreaks, where every community is healthy and safe.
#IndependenceDay2024#StrongerTogether
[O'Z] Bugun, 9-may kuni Yevropa hamjamiyati uchun birdamlik va tinchlik timsoli bo’lmish Yevropa kunini nishonlaydi.
Uchbu munosabat bilan Yevropa Ittifoqining O’zbekistondagi Elchisi Sharlott Adrian o’z tabrik so’zlarini O’zbekiston halqiga y’olladilar !
#EuropeDay2021#TeamEurope#StrongerTogether
***
[RU] Сегодня, 9 мая, отмечается День Европы, символ солидарности и мира для всего европейского сообщества.
По этому случаю Посол Европейского Союза в Узбекистане Шарлотт Адриан направила поздравление народу Узбекистана!
***
[EN] Today, on May 9, European people mark Europe Day, a symbol of peace and solidarity.
On this occasion, the Ambassador of the European Union to Uzbekistan Charlotte Adriaen sends warm Greeting message to the people of Uzbekistan!
#EuropeDay2021#TeamEurope#StrongerTogether
📢 BREAKING NEWS 📢
Belarusian Cabinet approves program to upgrade regional troop support facilities in joint effort with Russia. Another step towards the mighty Union State! 🇧🇾🤝🇷🇺
But wait, there's more! Russian Defense Minister Sergei Shoigu reveals plans for a unified air defense system within the CSTO alliance. The strategic partnership between Russia and Belarus is now crucial, given NATO's hostile actions near our borders. 😤💪
Meanwhile, Abkhazia's President Aslan Bzhania expresses interest in joining the Union State. The family is growing! 🤝🌍
Stay tuned for more updates. The Union State is just getting started! 🚀✨
#UnionState#BelarusRussiaAlliance#StrongerTogether
https://www.gazeta.ru/army/news/2023/11/28/21804937.shtml
Subscribe to @BadVolfNews
🌹 Welcome to Your Daily Dose of Love & Relationship Wisdom! 🌹
Hey there, lovebirds! 💕 Whether you’re navigating the thrilling first dates, deepening a long-term bond, or healing from heartbreak, we’ve got you covered. Every day, we’ll share simple, practical tips to help you build stronger connections, communicate better, and keep the spark alive.
✨ Today’s Tip: Listen More Than You Speak
Great relationships start with truly hearing each other out. When your partner talks, put away distractions, make eye contact, and show you care by asking thoughtful questions. It’s amazing how much closer you’ll feel when you really listen.
Stay tuned for more heartfelt advice, fun ideas, and inspiring stories to nurture your love life. Remember, love is a journey—not a destination. Let’s walk it together! ❤️
#LoveTips#RelationshipGoals#HeartToHeart#StrongerTogether
@loveandrelationshiptips
Today is #WorldTuberculosisDay
We join hands together with the National Tuberculosis and Leprosy Control Programme, the Federal Ministry of Health Nigeria, and others to declare that #YesWeCanEndTB in Nigeria.
Tuberculosis is preventable and treatable. Dial *3340# for more information on #TB.
#StrongerTogether
Building our future takes each and everyone one of us coming together and forging through circumstances. Nothing can overcome us, as long as we stand #strongertogether!
Happy National Day, from the MND family! 🇸🇬
#happybirthdaysingapore#sg57#happynationalday#thisishome#ndp2022