Что делать если нужно поставить какую-то 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
Terrorism: From now on, an African who supports Ukraine 🇺🇦, who itself supports terrorist groups in Africa and Mali 🇲🇱, is considered an enemy for the liberation of Africa. From now on, Ukraine is officially the enemy of Africa, and the pan-African community. We will effectively treat his case as we do with their ally France on African lands. Case to follow!
Any act of mercy towards Ukraine 🇺🇦 on African lands is equivalent to cruelty towards the African. #Understand Who Can Take Ukraine down! At the bottom of the USA 🇺🇸! Low down with the African Union! Slow the complicit African states!
The Revolution is on the Move ✊🏾
@egountchibehanzinTV
If you knew me,
This is what would you'd really find;
I'm scared,
I'm filled with so much hate.
You tell me to pick myself up,
but it's too late!
Dark is the only light in sight,
Slowly killing me,
Destroying me piece by piece.
I've lost myself completely,
Insecurities echo in my dreams,
Yearning to be set free.
It's fingers reach out,
Dragging me deeper,
Dragging me straight back to hell.
I'm sorry,
I'm sorry I'm a bad person.
I hate myself too,
I've never been good enough,
Not to myself and probably not to anyone.
I think I've had enough...
I wish you'd understand.
You don't understand.
You'll never understand.
#review#no#one#understand#me
Here are 5 key takeaways from the book
"STRATEGIZE TO WIN"
-
1. #Know your strengths and weaknesses. This is the foundation of any successful strategy. Once you know what you're good at and what you're not so good at, you can start to build a strategy that plays to your strengths and minimizes your weaknesses.
2. #Set clear goals. What do you want to achieve? What are your long-term and short-term goals? Once you know what you want to achieve, you can start to develop a strategy to get there.
3. #Understand your competition. Who are your competitors? What are their strengths and weaknesses? What are their goals? Once you understand your competition, you can start to develop a strategy that will give you an edge.
4. #Be flexible. The world is constantly changing, so your strategy needs to be flexible enough to adapt to change. Be prepared to adjust your strategy as needed.
5. #Execute your strategy. This is the most important step of all. Once you have a strategy, you need to execute it. This means taking action and making sure that your strategy is working.
Here are some additional key takeaways from the book:
A. #Strategy is not a one-time event. It is an ongoing process that needs to be reviewed and updated regularly.
B. #Strategy is not about perfection. It is about progress. You will never have a perfect strategy, but you can always improve your strategy by learning from your mistakes and by making adjustments as needed.
C. #Strategy is about execution. It is not enough to have a good strategy. You also need to be able to execute your strategy effectively.
I hope these key takeaways help you on your journey to strategizing to win.
💠Join 🔺 Share @Business_Idea4💠
Here are 5 key takeaways from the book
"STRATEGIZE TO WIN"
-
1. #Know your strengths and weaknesses. This is the foundation of any successful strategy. Once you know what you're good at and what you're not so good at, you can start to build a strategy that plays to your strengths and minimizes your weaknesses.
2. #Set clear goals. What do you want to achieve? What are your long-term and short-term goals? Once you know what you want to achieve, you can start to develop a strategy to get there.
3. #Understand your competition. Who are your competitors? What are their strengths and weaknesses? What are their goals? Once you understand your competition, you can start to develop a strategy that will give you an edge.
4. #Be flexible. The world is constantly changing, so your strategy needs to be flexible enough to adapt to change. Be prepared to adjust your strategy as needed.
5. #Execute your strategy. This is the most important step of all. Once you have a strategy, you need to execute it. This means taking action and making sure that your strategy is working.
Here are some additional key takeaways from the book:
A. #Strategy is not a one-time event. It is an ongoing process that needs to be reviewed and updated regularly.
B. #Strategy is not about perfection. It is about progress. You will never have a perfect strategy, but you can always improve your strategy by learning from your mistakes and by making adjustments as needed.
C. #Strategy is about execution. It is not enough to have a good strategy. You also need to be able to execute your strategy effectively.
I hope these key takeaways help you on your journey to strategizing to win.
Thank you for reading 📖