Что делать если нужно поставить какую-то 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
🔤🔤🔤🔤🔤🔤🔤2️⃣0️⃣2️⃣5️⃣
TON Fest 2025 is a 2-day immersive festival like no other. Dive into the world of #TON, take part in thrilling games, and compete for massive rewards. TON Society will be the Ecosystem Partner of this groundbreaking event!
Why you can’t miss it:
⭐️ Explore $TON like never before.
⭐️ Win incredible prizes and rewards.
⭐️ Join a community shaping the future of Web3.
⭐️ Exclusive giveaways for participants.
➡️️Tickets are available now.Be there, or miss out on the event everyone will be talking about! 💎
⭐️You will need Telegram Stars to buy a festival ticket and upgrade $MANA mining. 🚀
#TONFest#Web3
🔤🔤🔤🔤🔤🔤🔤2️⃣0️⃣2️⃣5️⃣
TON Fest 2025 is a 2-day immersive festival like no other. Dive into the world of #TON, take part in thrilling games, and compete for massive rewards. TON Society will be the Ecosystem Partner of this groundbreaking event!
Why you can’t miss it:
⭐️ Explore $TON like never before.
⭐️ Win incredible prizes and rewards.
⭐️ Join a community shaping the future of Web3.
⭐️ Exclusive giveaways for participants.
➡️️Tickets are available now.Be there, or miss out on the event everyone will be talking about! 💎
⭐️You will need Telegram Stars to buy a festival ticket and upgrade $MANA mining. 🚀
#TONFest#Web3
🚀 TON Fest Season 1 heats up with HoldCoin🎉
💥Win 6 Million Diamonds & $TON
🔥The longer you “hold”, the more you are rewarded
📆Sept 3-Sept 8, 4 AM UTC
👉HoldCoin mini app
Open SafePal App QuestHub to join the campaign now!
📱DL App: http://safepal.com/download
📚Learn more campaign detail
#SFP#TonFest#HoldCoin
Festival season with Ton Festival and CapsGame!
Our friends from ❤️CapsGame and
🔠TON Festival decided to join forces and launch a new season! A festive atmosphere, fresh activities, and, of course, a bunch of surprises — all this is already here!
What's ahead?
⚫️6 Cool Chips for Your Collection
⚫️ Huge edition — 20,000 chips
⚫️ Leaderboards and festival activities right in the game!
How to Earn you Tent Points 🏕
⚫️ Completing dailies: 10
⚫️ Mint of any chip: 50
⚫️ Chip Madness Round Completion: 5 (no repeats)
⚫️ Upgrade your chips to Legend+ and higher — the cooler the chip, the more points!
🏅Prize fund — tickets🎫 giving cool bonuses and exclusive items await those who collect the most points at the end of the season.
🗓️The final day of the event is March 27. The store opens on March 28th — exchange tickets for cool prizes!
🫶Become a part of the main event of the year!
#CapsGame#TONFest#Web3#TON
Bidask Protocol — New DEX on TONand a Giveaway💵33,000
🅱️Bidask launched in mainnet just a few days ago — before that, the exchange was in the testnet for almost three months. The team claims that their swap model is faster, cheaper and more efficient than its analogues. Practice confirms: exchanges are instantaneous, and the 10-15 sec delay is just the time it takes for the wallet to pick up the transaction. Further optimization is already on the TonCore side.
💰The seed investor is DWF Labs (market maker and validator #TON). For a young project, this is a serious resource — #DWF is building its own ecosystem and strengthening the platforms it is a part of.
#Bidask — partner 🌑#TONFest. The festival will feature a raffle 💵 33,000, and you only need to complete three tasks:
✔️Make $10 swaps
✔️Provide $10 to liquidity pools
✔️Provide $20 to liquidity pools (first $10 does not count). Your $20 is locked in the pool until June 30, 2025.
We recommend the $TON/$USDT pairand be sure to follow the buttons inside TON Fest — otherwise the quest will not be counted.
Bidask DEX | Channel
MyTonWallet v3.7 Update & $MY Birthday
💎 Overview of new features and changes:
🔵Expanded TON DNS support: You can now renew multiple domains at once, track their expiration, and link them to your wallet directly inside MTW.
🔵Mass transfers: Send up to 255 transactions at once — including via CSV file uploads.
🔵All token actions in one place: Long-press any token to open a contextual menu with all available options.
🔵Pin NFT collections: Access your favorite collections directly from the home screen — especially handy for Telegram gifts.
🔵USDe staking now live
🎉Happy 1st Birthday to $MY! On June 2nd, it’s been exactly 1️⃣ year since the community voted to launch the $MY utility token. The team shared a yearly recap and highlighted key milestones in #MyTonWallet’s journey.
🎁 To celebrate, all users holding at least 500 $MY can enjoy zero aggregator swap fees inside #MTW from June 2 to June 9! (Blockchain fees still apply.)
#MY#Update#TonFest
🌑TON Fest Extended Through May 28 — you still have time to complete quests and claim rewards from top Web3 Projects!
TON Fest is an immersive virtual world built with Telegram Mini Apps. Complete tasks, join activities, and earn on-chain rewards you won’t find anywhere else.
🎟Grab your ticket to unlock access to VIP zones, premieres, challenges, and exclusive prize pools!
#TON#Web3#Quest#TMA#VR#TONFest