Что делать если нужно поставить какую-то 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
✅Mark your calendar for exciting AMA!
Analyzing 2025's Biggest Opportunity 🔮
Join us today at 12 PM UTC with @CyberChargeJoe ,the Co-Founder of #CyberCharge🔋
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🎄The XMAS holiday season is here!🎁
#CyberCharge Wish you a holiday full of happiness and Gem in bag! 💎
Unlock up to 1500 USDT Gift
📱Join here:https://t.me/CyberChargeGroup
✨Power up,Earn More
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
Congrats 🎊CyberCharge Whitelist Event Ended Successfully!🔚
🔋You’ll enjoy a increase in charger revenue and have first access to profit sharing from the mining pool.⚡️CyberCharge orders are processing ,will be shipped over the next 30 days📆
#Cybercharge Brings the power of web3 charging and mining together!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🚆 The $GOUT train is on the move, and so are your chances to earn! Complete your first charge on #CyberCharge & share 1 MILLION $GOUT! 🤑
It’s easy:
🐦 Follow us & @GOUTCoin
🔋 Charge with the app + comment your APP ID below!
🔁 RT + Tag 2 friends
The market is heating up fast 🔥and so is the reward pool.
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🐾Meet AI Doggy, your loyal companion on the #CyberCharge journey! 🐕
✨Buy, grow, and earn with your digital pet
🔋Keep its health >50% for max mining rewards
💎Boost its value as you nurture it
⚠️Careful—if health hits 0, it’s game over!
Get Ready: https://link.medium.com/qzA4cxdp6Ob
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
↗️ROI So Quick, You’ll Blink Twice!
🔋Charging your devices is now a revenue stream. #CyberCharge makes it REAL with fast returns. Watch how you can earn in record time! 📽
💎Apply for the whitelist with Gem Shards in the Mini App today!
👉http://t.me/CyberChargeBot/whitelist
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🎉Celebrate our partnership with @arbitrum!🎉
To join:
1️⃣RT & Like this post
2️⃣Comment with your BEP20 wallet address and #CyberCharge TG ID
⚡️20 USDT x 5 winners! ⚡️
Get ready to Charge-to-Earn with CyberCharge on arbitrum! 💙🧡
🏆Winners announced in 3 days—don’t miss out! 🚀
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🔋CyberCharge x Movement is here!
⚡️By combining @movementlabsxyz ’s platform with #CyberCharge’s Charge to Earn technology, we’re making every charge count.
Now, users can earn rewards simply by staying powered up, all within a secure and engaging digital ecosystem.
Stay tuned for more!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🚀CyberCharge x EMC Partnership!⚡️We're thrilled to team up with@EMCprotocol to revolutionize blockchain-powered energy solutions!
EMC is a leading AI & DePIN platform that bridges the computing power network and decentralized AI applications!
🔋With the world’s first DePIN Charge-to-Earn (C2E) Network, #CyberCharge brings the power of charging and mining together!
Stay tuned for exciting updates as we unlock new paths for sustainable energy. 🌱
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
Global electricity usage is spiking after decades of stable demand. Now CyberCharge tackle the sustainable energy challenge. But how to earn your ticket to the next-gen of energy networks?
🎬 NEW VIDEO DROP: How to Earn with #CyberCharge!
🎁GIVEAWAY
We’re giving away 5 $USDT to 10 lucky winners!
1️⃣Follow & RT
2️⃣Open the link 👉t.me/CyberCharge copy your TG ID, and paste it here.
3️⃣Screenshot your favorite part of the video and post it below!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
🔋Ready to charge up your earnings? 💥
🤑Join the Charge-to-Earn event with #CyberCharge, where EVERYONE wins 100% guaranteed USDT rewards!
💰Earn NOW
🔗http://t.me/daily_gifts_en/74
Don’t miss out, it’s that simple: complete tasks & earn!
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube
👋Hey #CyberCharge mini APP users! We’ve rolled out some cool new updates:
✨Home upgraded with smooth new animations.
🛑 "Withdraw" button in My Assets now highlighted with extra safety prompts.
🎁Task interface refreshed: updated task lists and Mystery Box rewards shown per task!
💎Invite friends and earn even more Gem Shards!
🌐Global broadcasts—stay informed anytime, anywhere.
Update now for a smoother, safer experience!
🔋t.me/CyberChargeBot
🤖Earn NOW📱X(Twitter) 📱Chat💬Discord📱YouTube