Что делать если нужно поставить какую-то 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
👍 Happy Valentine's Day from #Nicegram!
Valentine's Day is all about sharing love, and what better way to do that than by inviting your loved ones to Nicegram? 📲
It's the gift that keeps on giving - not just connecting hearts but also rewarding you with gems! 💎
💗This Valentine's Day, let's make memories: Invite your loved ones to Nicegram and earn gems together!
#Nicegram is the perfect app for those looking to go beyond Telegram's standard functionality, offering enhanced messaging experiences with superior privacy features and customization options 🥰
💌GETA REFERRAL LINK
Happy Valentine's Day, everyone! Let love lead the way 💕
Follow us:✖️X | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
💸Vietnam Leads in Crypto Adoption, and Nicegram is Right There!
Vietnam's tech-savvy population is spearheading global crypto adoption, and #Nicegram is at the heart of it! ▶️
With 25M global users, including 3.6M in Vietnam, we're connecting the crypto community like never before.
💬 Dive into Sergey Sheleg's insights on leveraging Nicegram for Vietnam's crypto wave, and how we're revolutionizing engagement with web3 features ✉️
👉 READ THE FULL INTERVIEW
Follow us:✖️X | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
🆕New #Nicegram Update Alert
We're excited to announce our latest update - now running on the fresh and advanced Telegram 10.3.1 version! ⭐️
🌟 Introducing Nicegram Special Tasks:
🔸In the tasks section, you'll find a new option. Tap on it to discover a variety of tasks from advertisers.
🔸Choose any task you like, read the conditions, and complete the required steps.
🔸Once the advertiser confirms your task completion, gems are yours!
Effortlessly track the status of your rewards right from the menu.
It's that easy and fun! 🤡
Get ready to boost your gem earnings with these special tasks from advertisers!✨
🔗OPEN NICEGRAM PROFIT
Follow us:✖️X | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube | 📰Medium
🔄 Introducing Our Ambassadors 🔄
Say hello to our incredible ambassadors who are here to make your #Nicegram experience even more amazing! 🔝
Today, let's shine the spotlight on our first ambassador:
🌈 Kate (Busty Barbie)🌈
Meet Kate, our vibrant ambassador! With captivating charm and unparalleled wit, she injects a burst of fun into Nicegram.
Dive into her delightful presence for great conversations and lasting laughs!🔥
Stay tuned for more updates as we unveil the rest of our ambassadors! 😎
🔗CHECK THE AMBASSADORS
🆕The new #Nicegram update is available NOW!
Here are all of the exciting new features that await you 👇
🔹Update to Telegram 10.3 version
Nicegram now has the latest version of the Telegram source code.
🔹Nicegram Profit is now live!
Now you can earn Gems by inviting friends and completing tasks.
Use these Gems for a variety of rewards - from engaging with AI and creating images, to participating in auctions, or even converting them into cryptocurrency and prepaid cards!
Start exploring all the new possibilities with Nicegram!🔄
UPDATE NOW👇
🛒APP STORE | 🛒GOOGLE PLAY
🎉Join the #Nicegram Community Giveaway!
As we gear up for the upcoming Nicegram Profit, we're bringing you an awesome contest to boost your engagement and rewards! 🔝
📆 Dates: Dec 6 - Dec 14
📝Simple Rules:
🔹Join @nicegramapp
🔹Join @nicegramchat
🔹Chat away! Send 20+ meaningful messages. (Note: No stickers or basic hellos!)
💰 Prizes: 3 winners get 💵 20 USDT each!
💥But wait, there's more! Use your Referral link to invite friends and chat away in Nicegram. More chats, more chances to grab additional rewards!
Get ready to chat, refer, and win! 🏆
🔗OPEN NICEGRAM ASSISTANT
🌟 Exciting updates and exclusive content await you on #Nicegram!
🚀 Follow us on Twitter for the latest news and events before anyone else!
🔗x.com/nicegramapp
📣Don't miss out—join the Nicegram Twitter now! 🌐
Our socials:✖️X | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
❤️Did you know about Nicegram Navigation?
📌 Here at #Nicegram, we're on a mission to make your journey through Nicegram's world an absolute breeze!
Follow our 🔗@NicegramNavigation for a seamless experience — access all our official social media links, chats, and channels effortlessly 😎
🌐Join us today and simplify your Nicegram journey
🔗https://t.me/NicegramNavigation
❤️Choosing the Best Messaging Experience: Nicegram vs. Telegram 🚀
While Telegram has its strengths, Nicegram pushes the envelope to deliver a superior messaging experience. What sets Nicegram apart?
💬Unleashed Communication:
🔓Access blocked channels & groups, no VPNs required
🔞Experience chat freedom, no blocked conversations
📲Multiple account mastery; juggle personal, business, and more
💡User-Centric Features:
⚙️"Double Bottom" – Conceal your chats and accounts effortlessl
🧠Built-in ChatGPT assistant, LilyAI, ready to assist
🚀Unique chat enhancements: quick replies etc.
🌐Exclusive to Nicegram:
🔹Unique Nicegram assistant
🔹Virtual Сard benefits
🔹 An active Nicegram Community Hub
🔹 Enhanced chat with distinctive and spicy feature
Your chats, upgraded. Dive into the world of #Nicegram🌟
🔗https://nicegram.app
❤️Today’s Fact of The Day is here!
Ready to break the limits? 🚀
Roll up your sleeves because with #Nicegram, you can create an unlimited number of accounts, anywhere, anytime.
📲Separate work and personal contacts, and wear as many hats as you please!
How do you use this limitless feature of ours?
We can’t wait to hear your stories! 💬
🔗https://nicegram.app
Follow us: 🐦Twitter | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
❤️AI is revolutionizing our world in astonishing ways!
🔬 From detecting intricate health conditions to streamlining business operations, AI is the driving force behind numerous advancements.
📺 Think about the last time you binge-watched a series. Wasn't it AI that recommended it to you on your favorite streaming platform?
✨Such innovations only scratch the surface!
🦾 Among these leaps forward is LilyAI within the #Nicegram app. It's more than just a chatbot; it's your personal companion.
We are always improving LilyAI. It's already unique! 🌟
🔗nicegram.app/deeplink?url=ncg://aiLily
Dive deep into the world of AI with #Nicegram.
Follow us: 🐦Twitter | 📷Instagram | 📖Facebook |💼LinkedIn | 📹YouTube
❤️Level Up with Nicegram
In today’s world of 24/7 online communication, don’t let limitations dim your conversations! 💬
👉 Experience limitless Telegram messaging but on a whole new limitless level with Nicegram’s:
🌍 Global Unrestricted Access
🗣️Access to Blocked Channels and Groups
🤖 Ultimate and unique AI chatbot
📱Multiple Accounts on One Platform
🛡 Secure, Double-layered Encryption
🔄 Instant Voice to Text Transcription and Translations
💳Virtual card Integration
Ready to chat unrestricted, unblocked, and unleashed, whenever and wherever?
Download #Nicegram now and start chatting today!
🔗https://nicegram.app