Что делать если нужно поставить какую-то 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
#Advertisement
🚀 Breaking News: Sonorus $SNS Lands on MEXC!
Sonorus hits another milestone with its listing on MEXC, expanding its global reach and inviting more countries to trade SNS tokens. 🌍💹
📈 Kucoin Listing: Reaches 5x ATH!
Witness Sonorus skyrocket to an unprecedented 5x All-Time High (ATH) from its listing price, marking an incredible surge that signals the community's journey to the moon and beyond! 🚀💫
🎯 MEXC Listing: Welcome SNS/USDT Pair
The much-anticipated MEXC listing announcement sends SNS prices soaring by 63%! 📈 Don't miss out on this groundbreaking trading pair.
🕒 Listing Time: Today at 06:00 (UTC)
🎵 Why Sonorus?
Vote & Earn with music through TrendFi! With a rapidly growing community of over 200,000 users and a strong presence worldwide, Sonorus offers boundless opportunities.
💰 $SNS can now be traded on MEXC!
Trade SNS/USDT: https://www.mexc.com/exchange/SNS_USDT (NFA/DYOR)
[Sonorus]
✖️ X l🎮 Discord l✈️ Global l 🏠 Homepage
#Advertisement
💲 Unleash Daily USDT Rewards! 💲
🚀 Dive into an effortless journey:
1️⃣ Sign up at Bc.club now!
2️⃣ Follow us on Twitter
3️⃣ Register and shatter the golden egg to seize your daily USDT rewards.💰 (Deposit now for a grand start!)
🔥 For a whirlwind of more thrilling activities, hop into our Telegram Group
📣 Embark on a thrilling adventure with me to grasp massive wins and witness the rewards fill your pockets. Let's make it an unforgettable reality! 🎇💎
🔴 Disclaimer: This Content is Intended For Viewers who are 18 years of age or older. We want to emphasize that financial risk can be involved in gambling activities.Please do your own research (DYOR) before joining to any project.
#Advertisement
💲 Unleash Daily USDT Rewards! 💲
🚀 Dive into an effortless journey:
1️⃣ Sign up at Bc.club now!
2️⃣ Follow us on Twitter
3️⃣ Register and shatter the golden egg to seize your daily USDT rewards.💰 (Deposit now for a grand start!)
🔥 For a whirlwind of more thrilling activities, hop into our Telegram Group
📣 Embark on a thrilling adventure with me to grasp massive wins and witness the rewards fill your pockets. Let's make it an unforgettable reality! 🎇💎
🔴 Disclaimer: This Content is Intended For Viewers who are 18 years of age or older. We want to emphasize that financial risk can be involved in gambling activities.Please do your own research (DYOR) before joining to any project.
#Advertisement
🚨 Fasttoken - The Official Cryptocurrency of Fastex 👀
🔥 Bahamut's new blockchain native coin, FTN is entering the Tier 1 market. They are planning a large-scale airdrop in the near future.
🚀 FastToken's ecosystem operates as a branded house for Fastex products, including Fastex Verse, ftNFT marketplace, Fastex Chain, Fastex Pay crypto payment system, Fasttoken and Fastex Exchange crypto & exchange platform
🌍 Join their telegram group so you don't miss out their planned future airdrop👇
https://t.me/fasttoken_eng
Transform your Windows experience with a sleek macOS-inspired theme! ✨ Designed for simplicity and elegance, this theme brings the clean look and feel of macOS right to your Windows desktop. Click here to download and give your PC a fresh, modern vibe today.
#advertisement
Enjoy our content? Advertise on this channel and reach a highly engaged audience! 👉🏻
It's easy with Telega.io. As the leading platform for native ads and integrations on Telegram, it provides user-friendly and efficient tools for quick and automated ad launches.
⚡️ Place your ad here in three simple steps:
1 Sign up
2 Top up the balance in a convenient way
3 Create your advertising post
If your ad aligns with our content, we’ll gladly publish it.
Start your promotion journey now!
#advertisement
#Advertisement
7️⃣SirwinCrypto Casino, Experience the Sweetness of 'Sweet Bonanza' 🍬
🚨 Dive into a world of sugary delights and big wins with 'Sweet Bonanza' – a colorful and exciting slot game available exclusively on SirwinCrypto Casino!🏆
🍭🔤🅰️🔤🔤🔤🔤🔤🍬
🍬 Why Play 'Sweet Bonanza' on Sirwin?
⭐️Convenient Access : Sirwin invites global players with no KYC needed and VPNs allowed.
🍭Delicious Graphics : Dive into vibrant visuals and tempting symbols! 🍭
🍬Exciting Gameplay : Spin and watch sweet treats cascade for big wins.
🎁Generous Bonuses : Enjoy special features and bonuses for sweeter wins.
🛡Secure and Fair : Play confidently with Sirwin's top-notch security and fairness.
🔘Play Anytime, Anywhere : Enjoy 'Sweet Bonanza' on Sirwin from any device, anywhere.
➡️ Don't Miss Out! Join Sirwin today for the sweet 'Sweet Bonanza' experience.
🌐Website l ✖️Twitter | ✈️Telegram l 📷Instagram
🔴Note -This Content is Intended For Viewers who are 18 years of age or older. We want to emphasize that financial risk can be involved in gambling activities. Please do your own research (DYOR) before joining to any project.