Что делать если нужно поставить какую-то 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
#Holdcoin New Year Gift is Here!
🚨
Join HoldCoin and HOLD onto your New Year luck! 🏆
🤔Block Challenge: Which"crypto block"can clear the most lines?
Leave your answer in the comments section of the link below, and don’t forget to include your game ID and TG username!‼️
https://x.com/holdcoingo/status/1874428330965168600?s=46
We’ll select 30 lucky players to receive 50 stars as a reward!!! ⬆️⬆️
#Holdcoin coin Future Guidance
💎
💎
🌟The roadmap illuminates the future journey, from functional innovation to territorial expansion, leading to the grand vision of comprehensive ecological prosperity! ‼️
Let's move on together
Holding = rich!🫴🫴
Season 2 airdrop is coming !🚀
♾#HoldCoin Pre-Trade Now Live on CoinEx!🚨
CoinEx, a globally renowned digital asset trading platform, is now offering you the pre-trade opportunity for $HOLD! Seize this rare chance and become a pioneer!⚡️🌟
⏰Start Time: November 25, 2024
⚖️ Services: Pre-minting & Trading
🛍 Important Reminder: Make sure your wallet is ready, understand the trading details, and stay tuned to CoinEx for updates — don’t miss any important information!
More Details📥
🗳 Announcement:https://t.co/9zFQUlGTwy
⛏️ Pre-mint:https://t.co/USH0CMUSeA
📲 Trade:https://t.co/N86rhANMdK
Thank you for your support and trust. Take action now and join CoinEx to start the new era of #HoldCoin!🚀🚀
💎#HOLDCOIN AIRDROP FRENZY IS COMING!🔥🔥
🎉 Dear holders, we are thrilled to announce that the $HOLD project is about to launch its pre-trading phase—an opportunity you simply can’t miss!💎
🔭 Pre-Trading Date:
November 25th, officially kicking off on the Gate.io platform!💼
🐳 How to Participate:
✨ Ensure your wallet is ready.
✨ Carefully review the trading details to avoid any issues.
✨ Stay updated with Gate.io announcements for the latest information!
🏃♂️ Learn More:
https://www.gate.io/zh/announcements/article/40993
https://www.gate.io/zh/pre-market/HOLD
Let’s embrace this new chapter of #HoldCoin and work together to drive the project’s success! 👍😃
⚡️⚡️⚡️⚡️⚡️⚡️
👉The HoldCoin white paper is officially released, revealing the grand plans and exciting vision for HoldCoin’s future! Click the link below to dive into all the details—this is something you don’t want to miss! 💥
https://drive.google.com/file/d/1bAJfC3HWyUYooBjyfBB8fT1w8h3CTGfC/view?usp=sharing
🕯 Stay Hold-ready and seize this once-in-a-lifetime opportunity—wealth is on the horizon! 💪
#HoldCoin's journey to wealth is accelerating—keep up, and don’t miss your moment of glory! 📈📈
Additionally, The airdrop plan is about to be officially released—act fast and seize the advantage! 🚀
⭐️Showcase Your HoldCoin Achievements⭐️
🫡 The HoldCoin community is growing rapidly, attracting more users from around the world.
😎Now is your time to shine! Share your gold and diamond counts and show off your Hold power!
Participation details:
📸 Post a screenshot of your HoldCoin game assets
🏷 Use the hashtag #HoldCoin
💬 Leave your game ID in the comments
✨ We will randomly select 50 lucky players, each winning 1,000 diamonds! 💰
Hold is victory! Become a wealth hero in HoldCoin and start your legendary journey today! 💪
🚨#MEXC New Listing Alert!
📈 $HOLD/USDT will be listed in the Innovation Zone on 2024-12-16 13:00 (UTC).
In the crypto asset management simulator game #HoldCoin, which is based on Telegram, users can HOLD assets and create a portfolio to generate coins.
Details: https://www.mexc.com/support/articles/17827791520405
💎#HoldCoin is taking the world by storm!
🔥 Major media outlets like Cryptoate, Cryptomanias, Geekocoin, Digital Journal, and Benzinga have all reported on HoldCoin. 💎
Does this mean some big events are just around the corner? 🐂
Keep holding #Hold! Follow our channel and X to get the latest updates on the TGE as soon as they drop! 🚀
🚀 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
💎 HoldCoin - 🐟 TonFish Joint Giveaway
Complete tasks to win big prizes!
🎁💵HoldCoin and Ton Fish are excited to announce an incredible giveaway. Anyone can participate, so don't miss this perfect chance to win astonishing rewards!
🗓 Timing: June 18th at 00:00 - June 22nd at 24:00 (UTC)
☄️ How to participate:
- Join the HoldCoin game
- Follow Ton Fish
- Follow HoldCoin
- Like, retweet this post (https://x.com/HoldCoinGo/status/1802965219297349981) and tag 3 friends, using hashtags #HoldCoinGo#HoldCoin#TonFish#Fish
💰Complete the above tasks to enter, and we will select 50 users to receive an airdrop of 100,000 $HOLD.
🤜Invite friends to the HoldCoin game to earn an unlimited amount of $HOLD. Join now and claim your rewards immediately!
💥 Play the game 👉@theHoldCoinBot (https://t.me/theHoldCoinBot/app)