Что делать если нужно поставить какую-то 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
LinkedIn’da topilgan maslahat:
Professional o’sishni tezlashtirish va atrofdagilardan farq qilish uchun biror soha yoki yo’nalishda “go-to-person”ga aylanish. “Go-to-person” - biror muammo yoki savol tug’ilganda murojaat qilinadigan odam: yo’nalish kattaroq kodning bir qismi, test qilish, biror freymvork, Kubernetes, Docker, biror usul va hokazo bo’lishi mumkin. Shu yo’nalishni topish va shu bo’yicha hamma suyanadigan, boradigan odamga aylanish odamning professional o’sishiga juda katta yordam beradi.
@farhodjon#growth
🌍 In November 2022, the world’s population reached 8 billion for the first time, doubling in just 48 years since 1974—a record pace in human history for global population growth. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, India gained over 13 million people—more than the total population of some countries. This rapid growth boosts its status as the planet’s most populous nation. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, Ethiopia recorded the world’s highest annual natural population increase, adding nearly 2.7 million people in a single year—more than many countries’ entire populations. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Leading Crypto VC Firms to Watch in 2023
Thanks for the feature! 💥
We're proud to be part of this ecosystem.
It's a privilege to be part of this Web3 future.
Let's keep building! ✨
#investment#community#growth
🌍 Over one million people are added to the world population roughly every five days. The fastest-growing regions are now in parts of Africa, where birth rates remain among the highest globally. ✨
#demographics⚡#growth⚡#continents⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
Good morning, good morning! ☀️ Looks like Darius had a good night's rest and is feeling even better than before.
———
Stage 2, Part 1 of the growth drive! Thank you all for your contributions to this - it's still in the works, albeit slowly!
Stage 2, Part 2 is in the works!
#art#growth#nsfw#hyper
Russia expects 3.9 percent GDP growth in 2024
📌 This is the result of a set of applied policies in the field of finance, infrastructure development, digitalization, building a knowledge economy, and improving the level of education of the population.
📌 "It was noted (at the APEC summit - ed.) that in comparison with other regions of the world in the economy (countries - ed.) APEC feel quite comfortable. GDP growth rates in APEC countries exceed the global averageaverage" - Russian Deputy Prime Minister Alexey Overchuk
#news#russia#nido_russia#economy#growth
https://t.me/nido_russia
🌍 The city of Lagos, Nigeria, is predicted to become the world’s most populous city by 2100. Rapid urban growth could bring its population over 80 million, surpassing today’s largest cities. ✨
#population⚡#growth⚡#megacities⚡#urbanization⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
TON is an up-and-coming powerhouse that we're absolutely stoked about⚡
In this video, TON's Head of Incubation, Justin Hyun, shares some exciting insights about Ton Foundation and its role in the #ecosystem.
While TON is younger than other significant Layer 1 blockchains, its rapid #growth and evolution has led it to become one of the hottest projects in the #crypto market in the last month, and it appears that next year will be exciting for TON.
In terms of transaction speed and versatility, TON Foundation remains ahead of other Layer 1 blockchains. In addition to a quick block validation time, the blockchain provides several advanced scalability features, such as sharding support.
Needless to say, we are a fan of this amazing #work and we can't wait to see the innovations that TON is going to bring to this space in the coming years.