Что делать если нужно поставить какую-то 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
🎊🎉🍾🇳🇬🇷🇺
Our beloved organisation, NIDO Russia has been officially accepted as a full member of NIDO Europe yesterday evening 01.02.2025 by the overwhelming majority of the general house which is the supreme organ. We owe this success to our faithful members, the board of trustees, the chairmen Emeritus and stakeholders.
Recall that, a tiny group of people prevented this for many years, saying that we must be part of their cabal for our rights to be respected in Europe. We rejected their ideas and protocols, we refused to be gradually assimilated, we took our destiny in our hands, knowing God was on our side. Their condition for peace was that we stoop low and be under them. We rejected that kind of parasitic peace. This group said it was either their way or the highway. We chose the beautiful highway. You must not be a doctor or lawyer or teacher to be part of NIDO Russia or NIDO Europe. Every Nigerian legally residing in Russia has a right to apply to be part of us. Even those who may not yet be fully legal, it is not our duty to judge or condemn them, but rather to guide them (socioeconomically adapt them) towards legalisation and contributing positively to Russia and their families in Nigeria.
It is a huge lesson for us all. "Na who give up, na him lose".
Nevertheless, we are open to working together with everyone for our common good including those few people who worked against us. It is a new era.
What are the benefits of being part of NIDO Europe?
1. The interests of Nigerians in Russia can be represented on a continental level.
2. The interests of the Russian Federation which are also our interests as residents can be represented on a continental level
3. Better negotiating power with the government on matters important to us as Diasporans.
4. Better synergy of efforts towards national development, bilateral trade, foreign direct investments and human capital development.
I, on behalf of the executives congratulate us all for this huge achievement including those members who witnessed it live and direct.
Yours in service,
Dr. Godwin Ibe
https://t.me/nido_russia/1937
#NidoRussia#NidoEurope#NIDO#NidoE#Nigeria#Russia
NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online.
Benefits
✅ Take part in shaping Diaspora affairs on a continental level.
✅ Attendance is free
✅ Network with business partners around the European continent
✅ Make new friends/acquaintances
✅ Pitch your ideas
✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level.
Take advantage of this golden opportunity.
Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up.
Dr. Godwin Ibe,
Chairman, NIDO Russia
+79262385618
*This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom.
#nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm
NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online.
Benefits
✅ Take part in shaping Diaspora affairs on a continental level.
✅ Attendance is free
✅ Network with business partners around the European continent
✅ Make new friends/acquaintances
✅ Pitch your ideas
✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level.
Take advantage of this golden opportunity.
Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up.
Dr. Godwin Ibe,
Chairman, NIDO Russia
+79262385618
*This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom.
#nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm
NIDO Europe invites all members of NIDO Russia to an extraordinary general meeting. It will be held online.
Benefits
✅ Take part in shaping Diaspora affairs on a continental level.
✅ Attendance is free
✅ Network with business partners around the European continent
✅ Make new friends/acquaintances
✅ Pitch your ideas
✅ The most active unofficial participant from NIDO Russia positively representing our interests will receive a token of appreciation for voluntary contribution to the diasporan affairs on a continental level.
Take advantage of this golden opportunity.
Registered members can simply send me a short message saying "I'm interested", and we'll do the rest and hook you up.
Dr. Godwin Ibe,
Chairman, NIDO Russia
+79262385618
*This is a requisitioned EGM by members in accordance with the act of Parliament in the United Kingdom.
#nidoe#nidoEurope#nidorussia#nido#NigeriansInDiaspora#egm