Что делать если нужно поставить какую-то 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
⚡️DAOLama NFT Lending: APY Increased to 3.64%
#TON#DAOLama
DAOLama NFT Lending announces an increased APY of 3.64% for their vault, offering higher yields for TON holders. With current liquidity being utilized efficiently, the deposit limit is set at 150,000 TON.
Source: link
@tonlines
DAOLama NFT Lending: Deposit Reopening in DAOLama Vault
#DAOLama#TON
DAOLama NFT Lending announces the reopening of deposits in the DAOLama Vault. With almost 100% utility reached, the channel invites users to take advantage of the new 150,000 TON limit and growing APY ahead of upcoming events.
Source: link
@tonlines
⚡️DAOLama NFT Lending: Buy TG Stars and Premium with TON
#TON#DAOLama
DAOLama NFT Lending has introduced the option to purchase TG Stars and TG Premium using TON directly within the DAOLama App. This update simplifies purchases, eliminating KYC requirements and supporting USDT in the next update.
Source: link
@tonlines
⚡️DAOLama: Final Days of Anonymous Telegram Numbers Contest
#Telegram#DAOLama
DAOLama announces that there are only three days left until the end of the Anonymous Telegram Numbers Contest. Participants are reminded of the special annual interest rate of 10% on loans available until the event concludes. Partners provide additional offers to boost points.
Source: link
@tonlines
DAOLama NFT Lending: Activate Your SBT Discounts
#DAOLama#SBT
The DAOLama NFT Lending channel announces the activation of discounts for SBT Tier-1, Tier-2, and Tier-3 tokens. Users can use the DAOLama App to claim their discounts and apply them to loans with Anonymous Numbers.
Source: link
@tonlines
DAOLama x CapsGame: Launch of 'Follow the Lama' Season
#DAOLama#CapsGame
The DAOLama NFT Lending (@daolama) channel announces its collaboration with CapsGame for the launch of the 'Follow the Lama' season. Players can now use DIAMOND chips as collateral to gain liquidity on the DAOLama App. The new season features exclusive tasks, a leaderboard, and rewards that include converting lama points into tickets for valuable in-game items.
Source: link
@tonlines
🦙DAOLama Team x TON Society Event!
This month is set to be special for all Telegram Anonymous Numbers holders 🐶
Together with TON Society and leading DeFi partners, the DAOLama team has prepared a massive event that will grant number holders exclusive opportunities and benefits within the TON ecosystem 🤟
🏆Prizes & Rewards
🥇Zero-fee liquidity
🥈50% discount on fees
🥉25% discount on fees
🐷SBT & Lifetime Bonuses
🏆Top-10 – 10% discount
💎 Top-50 – 7% discount
💎 All participants – 5% discount
🪙Upgraded Benefits:
🟢Enjoy a reduced 10% interest rate (only during the event).
🟢Extended loan period of up to 2 months.
How to participate?
✅ Prepare a wallet with your Telegram Anonymous Numbers NFT
✅Take a loan on DAOLama and use TON in DeFi projects
✅ Track your position on the Leaderboardand accumulate points
Bonus Points from Partners
🤝Tradoor – 0.25 points per TON provided
🤝Ston.fi – 0.25 points per TON provided
🤝Rainbow.ag – 0.25 points per TON exchanged
🗓️The contest is live – don’t miss your chance!
🦙Join DAOLama now!
#DAOLama#SBT#DeFi#TONSociety
🪅DaoLama launched vault in TON with APY 40% and announced the $LLAMA holder incentive program
❤️ A function has appeared to provide liquidity in the TON token, where 80% of the income from each issued loan is distributed among the owners of $DLP (contract address). APY's annualized return is currently ~40%. If you don't know what this means yet, we encourage you to read our post on the topic — What is the difference between APY and APR?
Recently, the team announced an incentive program for holders of the $LLAMA project token — regular repurchase of coins from the market directly through #DEX, which is very important, and sending these tokens to their holders.
↗️ As the project grows, the ransom amounts will increase, but the dates will be kept secret to avoid manipulation of the coin rate. So in the long run it sounds very tasty for #LLAMA.
And now the most interesting...
❤️ Each user who follows our referral link will receive a 100% discount, as well as 10% more $TON for the first loan or purchase on credit on the DaoLama marketplace.
#DaoLama#staking#TON
💛 Storm joins the 🦙 DAOLama contest!
We previously shared details about the DAOLama Team x TON Society event, which unlocked unique opportunities for holders of Telegram Anonymous Numbers
🐸Now, Storm Trade is joining the initiative — meaning you can now earn additional leaderboard points by using your TON-backed loans directly on the #Storm platform!
Here’s how it works:
⚫️ Use your Telegram Number NFTs as collateral to borrow TON
⚫️ Earn 1 point on the leaderboard for every 1 TON borrowed
⚫️ Trade on Storm Trade with margin in TON to gain +0.25 points for each TON used
⚫️ Climb the leaderboard and earn rewards and utilities from DAOLama
🤝Storm and DAOLama are teaming up to bring even more opportunities to participants — don’t miss your chance to get involved!
#DAOLama#SBT#DeFi#TONSociety#StormTrade