Что делать если нужно поставить какую-то 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
After falling from the support level of $500.0, #BinanceCoin reached the support level of $400.0 and recovered and is now trading above both levels.
As you can see in the chart, a dynamic resistance still prevents #BNBUSDT growth, so in the first step, crossing and breaking this resistance can be a sign of the continuation of the upward trend in the daily time frame.
So far, BNBUSDT has hit the dynamic resistance 2 times and failed to break it, these collisions may reach up to 5 times and then the price will start to grow. The current price movement scenario is between the $400.0 support and the dynamic resistance.
Easily earn a small income, Tencent PP Ranch Golden Egg Picking Guide!
Dear QQ Ranch friends, today, we are going to share how to easily make money in Tencent PP Ranch by picking up golden eggs! Just a few steps to make your virtual farm more abundant, earn money now!
————————
📚 1. Understand how to get golden eggs
First of all, golden eggs are a rare resource in QQ Ranch, which are picked up by participating in daily activities, completing tasks or within a specific time period. Remember to go online regularly to ensure that you don’t miss them!
📚 2. Improve the efficiency of picking eggs
⦁ Reasonable time arrangement: Choose the peak period of popularity to enter the game, and the chance of getting golden eggs is greater.
⦁ Add friends: help other players and share the experience and skills of picking eggs.
📚 3. Trade with golden eggs
The golden eggs you pick up can be sold through the in-game trading system to get game coins or other rewards. Pay attention to market trends, choose the best time to make a move, and maximize your profits!
📚 4. Participate in activities to get more rewards
Regularly participate in various activities of Tencent PP Ranch, and there will often be extra golden egg rewards to increase your small treasury. Pay attention to game announcements and participate in time!
📚 5. Continue to invest and enjoy the fun
Persist in going online every day, enjoy the fun of picking golden eggs, accumulate wealth, and make more like-minded friends.
————————
Come and pick up golden eggs at Tencent PP Ranch and earn your wealth! Perseverance, simple earning, and a promising future! 🎉
If you have other successful experiences in picking golden eggs, please share them in the comment area! I wish you all a happy game and full profits!
https://t.me/TencentPPRanch_bot/ppp?startapp=477789
#Bitcoin#Ethereum#BinanceCoin#Tether#XRP
#CorporateSocialResponsibility
#EmergingMarkets#Cardano#Solana
#CrossCulturalBusinessPractices
#Tencent PP Ranch
#Tencent PP Ranch Registration
#Tencent PP Ranch Official
#Free to play
#Free benefits
Tencent PP Ranch is an online simulation experience of ranch management game developed by Tencent. The initial version can give you the experience of adopting robot chickens, laying eggs, grabbing eggs, and stealing eggs, allowing you to relax through the game during a busy day. "Each egg obtained has a corresponding value"
🛒Official exclusive customer service telegram:
1️⃣t.me/TPR_005
2️⃣t.me/TPR_003
#Ethereum#Bitcoin#BinanceCoin#Tether#XRP#Cardano#Solana#Dogecoin#Polkadot#Chainlink
#ENJ#ICP#XTZ#UNI#XLM#MATIC
#Free rewards#Free community creation#Tencent PP Ranch Customer Service#Tencent PP Ranch Cooperation
#Free USDT withdrawals
#Free game resources