Что делать если нужно поставить какую-то 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
🪙Дайджест новостей 🪙
💎 NOTCOIN:
1-2 ноября в Дубае пройдет главное ежегодное событие для сообщества TON — конференция The Gateway, где выступит Саша (Notcoin). Недавно на канале Notcoin был опубликован тизер запуска лаунчпула для стейкинга, и, возможно, завтра Саша поделится подробностями об этом во время своего выступления.
▶️Ссылка на прямую трансляцию
🐶 DOGS:
😎 Собаки завоевали две главные награды на #BlockchainLife2024: «Мем-монета года» и «Проект года Tap-To-Earn».
🏴☠️ Кроме того, $DOGS объявили охоту за сокровищами! Задача: собрать команду, искать и разгадывать подсказки, спрятанные в социальных сетях и знаковых местах по всему миру. Цель? Разблокировать скрытый кошелек с 13 000 000 токенов $DOGS!
Подробнее: https://t.me/dogs_community/196
🏴 NOT PIXEL:
🍽️ В пикселях стартовал Хэллоуин, и команда намекает на скорый листинг?
В одном из последних постов они написали:
Время идет, и $PX уже на горизонте, не так ли? Теперь мы движемся к крупным событиям.
🧨 А еще, в честь Хэллоуина вас ждут тыквенные бомбочки в подарок (6 шт.)! Каждая бомбочка приносит +196 $PX. Дополнительные бомбочки можно приобрести в игровом магазине по отличной цене: они стоят дешевле, чем молния или динамит, но приносят больше прибыли.
Холст уже превратили в настоящий тыквенный суп 🎃
👻
👻
👻 Кстати, если присмотреться, над холстом летают несколько привидений. Нажав на одно из них, можно собрать часть головоломки. Соберите все части, чтобы открыть доступ к секретному каналу.
🌚LOST DOGS:
🐕 Команда Lost Dogs написали большую статью-манифест, в которой рассказали о листинге, своих принципах и токене $WOOF.
Из интересного:
• Большая часть токенов достанется сообществу.
• Компания продолжит развивать основную коллекцию Lost Dogs, 50% роялти будет направлено на откуп и сжигание $WOOF.
• Lost Dogs начнет с низкой капитализации и планирует расти за счет развития продуктов, механизмов дефляции и новых партнерств.
🚩 X EMPIRE:
Сегодня последний день вывода $X на кошелек. Прием заявок заканчивается в 12:00 UTC.
Подробнее: https://t.me/empirex/418
Catch our Managing Partner, Andrei Grachev on stage at #BlockchainLife2024 in Dubai.
Join 8000+ attendees at the Crypto Event of the Year.
P.S. Quote GRACHEV to get 10% off any ticket.
Get your tickets here.
⚡️ Blockchain Life 2024 in Dubai!
The legendary Blockchain Life 2024 forum returns to Dubai on October 22-23. As Dubai solidifies its position as a global crypto hub, #BlockchainLife2024 will be the central crypto event of the year, bringing together key industry representatives worldwide.
With the bull cycle underway, participants have a prime opportunity to maximize their income before the peak of growth.
💎 Event Highlights:
Presentations by key speakers, panel discussions, and master classes on the latest crypto trends, blockchain technologies, and trading strategies.
Exhibition featuring leading mining companies and innovative startups.
Startup Pitch: Present your ideas to investors and funds.
Afterparty: Network with industry leaders and enjoy a performance by Alan Walker.
📆 Date: October 22-23, 2024
🚀 Place: Festival Arena, Dubai, UAE
Register Now
⚡️Blockchain Life 2024 will take place in Dubai ahead of the peak of the bullrun
The legendary Blockchain Life 2024 forum returns to Dubai on October 22-23. As Dubai increasingly asserts itself as a global crypto hub, #BlockchainLife2024 will undoubtedly become the central crypto event of this year, bringing together key industry representatives from around the world in the crypto capital.
The bull cycle has already begun, but the long-awaited peak of growth is still ahead, so forum participants have a great opportunity to maximize their income.
More than 10,000 people from 120 countries will meet at the forum to explore new earning opportunities.
💎The forum program includes presentations by key speakers, panel discussions and master classes. You will be able to learn about the latest trends in the cryptocurrency field, innovative blockchain technologies and effective trading strategies.
💎The exhibition will bring together leading mining companies providing equipment and services, as well as startups presenting their projects to investors.
💎Startup Pitch is a unique opportunity for startups to present their ideas to investors and funds.
💎Afterparty is a legendary event featuring world-famous musician Alan Walker, where you can network with industry leaders in an informal setting.
📆Date: October 22-23, 2024
🚀Place: Festival Arena, Dubai, UAE
Registration:blockchain-life.com
🎫 Buy a ticket at the lowest presale price using the promotional code TONEVENTS
#TON#conference#blockchain#crypto#forum#Dubai
⚡️Electra: Big Wins in Dubai🇦🇪
Long trip to Dubai is over. The team attended countless events and took the stage as speakers at top conferences.
Outcomes:
⏺Electra won the 🏆 "Best Startup" awardat Blockchain Life.
⏺Electra set up its own booth at #BlockchainLife2024, where the team showcased the trading terminal and hosted interactive sessions with guests.
⏺ Electra joined Headliners’ Dubai Rally, cruising alongside more than 100 supercars and much more.
🤔 With a network of valuable connections, the team are now in talks with top VCs and preparing for major collaborations.
Join now & Keep farming🚀
#winner#award#VC#DEX#trade#Dubai#events#airdrop
🪙October 22-23 — Blockchain Life 2024 in Dubai
The legendary Blockchain Life 2024 forum is returning to Dubai on October 22-23. As Dubai increasingly asserts itself as a global crypto hub, #BlockchainLife2024 will undoubtedly become the central crypto event of the year, gathering the top industry representatives from around the world in the crypto capital.
The bull cycle has already begun, but the long-awaited peak of growth is still ahead, so forum participants have a great opportunity to maximize their income.
More than 10,000 people from 120 countrieswill meet at the forum to explore new earning opportunities.
🎙Speakers
Justin Sun - Founder of #TRON
Paolo Ardoino - CEO #Tether
Yat Siu - Co-Founder of #Animoca Brands
Pascal Gauthier - CEO #Ledger
Dr. Marwan Alzarouni - CEO of #Dubai Blockchain Center
Xinxi Wang - Co-Founder of #Litecoin Foundation
Sunny Lu - CEO #Vechain
Arthur Breitman - Co-Founder of #Tezos
Eowyn Chen - CEO of #TrustWallet
Sasha Plotvinov - Founder of #Notcoin💎
🎓Forum program
The forum program includes keynote speakers, panel discussions, and master classes. You will be able to learn about the latest trends in the cryptocurrency sphere, innovative blockchain technologies, and effective trading strategies.
⚡️The exhibition will bring together leading mining companies providing equipment and services, as well as startups presenting their projects to investors.
⚡️Startup Pitch is a unique opportunity for startups to present their ideas to investors and funds.
⚡️Afterparty — a legendary event featuring a world-famous musician🎵Alan Walker , where you can connect with industry leaders in an informal setting.
📆When: October 22-23, 2024
📍Where: Festival Arena, Dubai, UAE
Registration:blockchain-life.com
🎫Buy your ticket now at the lowest presale price with promo codeTONEVENTS👉
#BTC#TON#ETH#conference#blockchain#forum#networking