Что делать если нужно поставить какую-то 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
NuDeFi.io transforms decentralized finance, merging privacy and blockchain. Explore unique adult NFTs, combining private transactions and financial security. Redefine your decentralized experience. Join us on the web3 journey in 2024.🚀🚀🌟🌟🎁🎁🎉🎉
Telegramhttps://t.me/Nudefi_Chat
#NuDeFi#Web3Revolution
https://pancakeswap.finance/swap?outputCurrency=0xe1987271a2838E7CaDEd3625Fe8B1Be714084Caf🚀🚀🚀🚀🎁🎁🎉🎉
🚀 Unveiling the Power of #UXLINK Ecosystem! 🌐
Dive into a world where AI innovation, DeFi, Game & Social collide – all powered by an amazing partner lineup!
Our Social Growth Layer, One Account One Gas(OAOG) & LinkToEarn protocols supercharge ecosystem growth. Whether you're into AI apps, agent infra, RWA, trading, data security, or immersive gaming/social experiences – there's a spot for every #Web3 enthusiast.
With 500+ stellar partners, we're redefining what's possible.
Join us and explore the future of Web3 with UXLINK!
#Web3Revolution#UXLINKSeason4
🎧⤴
🤑TON Ecosystem on Fire! Major Updates from Fintopio, TBook, and XDAO You Can’t Miss
This week, the TON blockchain ecosystemrolled out exciting updates across three projects: Fintopio, TBook, and XDAO. Fintopio, one of the fastest-growing DeFi wallets on Telegram, now has 6 million active monthly users, offering fee-free transfers and NFT storage. TBook introduces free TON WISE Credit Scores, encouraging users to showcase their onchain and offchain activities for potential rewards. Lastly, XDAO is pioneering the first DAO ecosystem on TON, integrating Telegram mini-apps and introducing community-driven farming games to attract new users. TON’s rapid growth continues, with a thriving Web3 community ready to reshape digital finance.
Chorus:
We on TON, leveling up the game,
Fintopio's flexin’, ain’t nothin' the same.
TBook’s credit stack, XDAO’s on the rise,
Decentralized future, right before your eyes.
Verse 1:
From Telegram straight to the blockchain scene,
Fintopio’s the wallet that’s keepin' it clean.
Millions logged in, sending cash for free,
DeFi on your phone, simple as can be.
$HOLD points stackin’, rewards gettin’ high,
Move fast, earn big, touch the sky.
Security tight, but the game’s still smooth,
Digital assets now got nothin' to lose.
Chorus:
We on TON, leveling up the game,
Fintopio's flexin’, ain’t nothin' the same.
TBook’s credit stack, XDAO’s on the rise,
Decentralized future, right before your eyes.
Verse 2:
TBook’s in the mix, building up your score,
Onchain data, you got rewards in store.
Credit's climbing high, opportunity knocks,
Show what you’ve done, you control the stocks.
Airdrops comin’ in, WISE Credit the key,
Exclusive deals, it’s the place to be.
You a star on the rise, now the world’s in view,
Link up your past, and the rewards come through.
Chorus:
We on TON, leveling up the game,
Fintopio's flexin’, ain’t nothin' the same.
TBook’s credit stack, XDAO’s on the rise,
Decentralized future, right before your eyes.
Verse 3:
XDAO’s movin’ fast, DAOs on the map,
Farming those coins while you sit back and tap.
Mini apps in play, communities grow,
TONxDAO tech, let the future flow.
Buildin' syndicates, big moves you choose,
DAO-based biz, ain’t no time to snooze.
Empowerin’ users, decentralize it all,
New age of finance, watch the empires fall.
Chorus:
We on TON, leveling up the game,
Fintopio's flexin’, ain’t nothin' the same.
TBook’s credit stack, XDAO’s on the rise,
Decentralized future, right before your eyes.
Bridge:
No more middlemen, we takin' control,
In the TON ecosystem, we’re playin' the role.
From wallets to scores, and DAOs takin' flight,
It’s a Web3 revolution, we shine in the night.
#TONBlockchain#DeFiTakeover#Web3Revolution
#TONCryptoNewsRapStyle
🎧@toncoin_rap
🎧⤴
🤑Memelandia Revolution: Get Ready for Meme Battles, Prizes & Airdrops!
TON Memelandia is taking the memecoin world by storm at Token2049, evolving into a decentralized land where communities thrive on memes. With the launch of Cabal Arena, Memecoin Mountain, and more, expect epic battles between traders, creators, and memecoin communities. Major announcements, giveaways, and airdrops will ignite the meme revolution. Prepare for the ultimate Web3 engagement with tools that make launching memecoins easier than ever, with zero coding required!
Chorus:
Memelandia's rising, memes be flyin' high,
Battle in the Cabal, see who’s gonna ride.
Coins drop like rain, community’s tight,
We on the mountaintop, shining all night.
Verse 1:
In the Cabal Arena, the traders collide,
Meme battles lit, like a wild ride.
Community strong, got the mountain in sight,
Climb to the peak, under the spotlight.
Airdrops hit, prizes on deck,
TON’s memecoin, what did you expect?
Fair fights, no scams, no rug in sight,
Launch your coin, make the market ignite!
Chorus:
Memelandia's rising, memes be flyin' high,
Battle in the Cabal, see who’s gonna ride.
Coins drop like rain, community’s tight,
We on the mountaintop, shining all night.
Verse 2:
Launchpad’s hot, with a touch of a click,
For less than a buck, your coin can stick.
No-code tools, easy as can be,
Build your meme dream, and set it free.
Community forest, we gather the crews,
Spaces go wild, spreadin' the news.
TON’s the future, revolution’s begun,
We’re stackin' memecoins, ready to run!
Chorus:
Memelandia's rising, memes be flyin' high,
Battle in the Cabal, see who’s gonna ride.
Coins drop like rain, community’s tight,
We on the mountaintop, shining all night.
Verse 3:
Big rewards, liquidity flyin’ around,
Hold your memecoins, watch them compound.
TON Foundation, leading the way,
Memelandia’s here, and it's here to stay.
With every battle, the stakes get higher,
Communities reign, and the tokens catch fire.
Fair launch or presale, the choice is yours,
Join the revolution, and open new doors!
Chorus:
Memelandia's rising, memes be flyin' high,
Battle in the Cabal, see who’s gonna ride.
Coins drop like rain, community’s tight,
We on the mountaintop, shining all night.
Bridge:
Memecoins flow, through Telegram’s might,
Communities glow, shining so bright.
TON’s got the tools, we breaking the chains,
In Memelandia, only greatness remains!
#Memelandia#MemeBattle#Web3Revolution
#TONCryptoNewsRapStyle
🎧@toncoin_rap
🚀🌟 Vone's $100K Sweep Competition Launch! 🌟🚀
👋 Hey Community!
🎁 Join the Epic Vone Sweep Competition! Be among the first to dive into the future of Web3 communication.
Why Join?
🥇 Early Bird Advantage: Grab your chance to shape the Web3 world!
🎉 Amazing Prizes: Win cash and unique Vone numbers - your new digital ID!
🔐 Exclusive Whitelist Access: Get ahead in the Vone ecosystem.
How to Win?
📝 Sign Up: Register our Sweep Widget link.
🌐 Engage & Earn: Complete tasks, earn points, climb the leaderboard!
🏆 More Participation, More Chances!
Be a Web3 Pioneer!
Vone is more than a platform; it's a revolution in secure, blockchain-based communication.
🌍 Join the contest, win prizes, and lead the Web3 revolution!
⏰ Limited Time Only! Don't miss this unique chance to be an early Vone adopter.
🔗 Join our Sweep Now
🎁 Join Vone's Telegram for Daily Giveaways!
🌐 Vone's Homepage
📄 Read the Whitepaper
Together, let's make history with Vone! 🚀🏆
#VoneGlobal
#SweepCompetition#BeAnEarlyAdopter#Web3Revolution
Unlock the future of your digital world
Linking your crypto wallet to the Web3 network isn't just a step-it's your superpower to own your data, trade NFTs seamlessly, and dive into DeFi like a boss.
Start today and step into a decentralized tomorrow where YOU hold the keys!
#Web3Revolution
#web3forbieginners
#web3
#web3security
#web3technology
ADVENTURCKE