Что делать если нужно поставить какую-то 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
Unleash Your Inner Beast in the DINO League 🦖
Only the most powerful and cunning dinos rise to the top in #Crackasaurus ' DINO League. Prove your might, conquer challenges, and earn legendary rewards in this ultimate league. The DINO League is where true legends are forged.
Epic Rewards Await:
Earn colossal amounts of $CRACKA as you climb the ranks and get the 700K $Cracka for joining today.
Do you have what it takes to dominate and become a true legend?
🤑Join the Game here: @MappasaurusAppBot
Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🦖Bone Voyage to the Bone League Players...
Jurassically good rewards await the most skilled Dinos in#Crackasaurus. This ain't for the faint of spine, Test your mettle, Get$CRACKAand become a legend amongst dinos. Big Rewards are incoming.
🦕 Ready to rattle your rivals?
🤑Join the Game here: @MappasaurusAppBot
𝕏 Click to share it with your friend
👀Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🔥Dino Dominators! This is your chance to RULE the #Crackasaurus leaderboard 🦖
✨For the next 24 HOURS, share your epic referral link and code with friends, family, and earn 3x $CRACKA per recruit!
⏳ Don't miss this limited window to MEGA-BOOST your$CRACKAstash⚡️
Spread the word and start raking in those TRIPLE rewards!
🤑Join the Game here: @MappasaurusAppBot
🐦Click to share it with your friend
👀Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🦕 Fossil League
Start your Crackasaurus journey and unlock the gates to#Crackasaurus. This entry-level league is perfect for new adventurers. Discover hidden treasures and fossils, laying the groundwork for greater challenges. Ready to embark on an epic adventure? 🌟
🤑Join the Game here: @MappasaurusAppBot
🐦Click to share it with your friend
👀Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🎉 Egg-Ceptional Milestone 50,000 Gamers have joined the epic journey of#Crackasaurus🦖 tapping out a whopping 9.2 B taps along the way. Thanks for being egg-straordinary players. Keep tapping, cracking, and stacking those$CRACKA. Big surprises ahead 🎁
🤑Get Cracking: @MappasaurusAppBot🦕
🐦Click to share it with your friend
👀Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
We've reached a milestone!
#Crackasaurus now has
🟢10000+ gamers! 🎮
Next $NOT is cooking
😔.
Don't miss the opportunity. Early adopters get extra perks!
🌟
Come aboard and let's hatch, collect & win BIG: @MappasaurusAppBot📱
Check out our latest Twitter Post
✉️Chat❌Twitter
📰Medium
📷Instagram
📄Linkedin
🎁Earn
🎮 Over 1,000 gamers have joined the #Crackasaurus journey in the first 4 hours of our beta launch today. Play Crackasaurus on Telegram and let's make history together! 🦕
🥚 Crack those eggs and claim your rewards!
Play Today: @MappasaurusAppBot
Check out our latest Twitter Post
Follow us on;
Twitter | LinkedIn | Instagram | Youtube | Medium
Start Tappin, get Crackin. 🥚
Quit Doomscrolling and put those thumbs to some good use and mint $CRACKA
Eggs are waiting to be Cracked. 🦖
Play Now- https://t.me/MappasaurusAppBot
#Crackasaurus is all set for a dino-mite launch.
Read all about it- https://shorturl.at/fDJY6
Check out our latest Twitter Post
Follow us on;
Twitter | LinkedIn | Instagram | Youtube | Medium
🦖DINOS, now we have a 1 BILLION eyes on us 🌍👀
Thrilled to announce that #Mappasaurus App is now officially listed on the Telegram Apps Center.
Explore #Crackasaurus, our Tap2Earn game.
Crack Eggs, Earn $Cracka
and have endless fun—all within the @Telegram
✉️
🤑Play the Game here: @MappasaurusAppBot
Click to share it with your friend
Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🤑#Crackasaurus: Team Up & Multiply Rewards with New Invite Milestone Feature 🎉
🚀 Crackasaurus introduces a new invite milestone feature. Partner up with friends and unlock rewards that multiply. Every friend you invite pushes you closer to key milestones, and with each milestone reached, the rewards multiply!💥
🤝 It's teamwork time in Crackasaurus—don’t miss out on this exciting new way to play together and maximize your prizes!
👀Connect With #Mappsaurus :
🤑Join the game: @MappasaurusAppBot
Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🌍Global Communities
ASCEND to the Jurassic League!
Every DINO dreams of the #JURASSIC. Roaring arenas, legendary battles, and the ultimate test of claw and cunning. In #Crackasaurus Jurassic League, that dream CRACKS OPEN!
DOMINATE the ARENA and CLAIM your MOUNTAIN of $CRACKA. Become a LEGEND whose name echoes through the ages.
🤑Join the Game here: @MappasaurusAppBot
Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🌍Global Communities
🔈BREAKING NEWS!📲
The ultimate #Crackasaurus update is here 🦖
🤑
🤑#Tap | #Collect | #Earn
🔥Jaw-dropping New UI & Rewards!
⚡️Faster, Smoother Tapping Experience!
🪙Daily Quests with Extra Rewards!
🎁Exclusive Early Adopter Bonuses!
📈 Join millions of gamers and lead the tap-to-earn revolution!
🕹Play Here: @MappasaurusAppBot
📰Medium Article:Click here
📱Click to share it with your friend
👀Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn