Что делать если нужно поставить какую-то 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
⚡️Catizen Announcement: Animoca Invests in Catizen for Web3 Gaming Expansion
#Telegram#Bombie#Animoca
Animoca Brands has made a major investment in Catizen, a popular Telegram-based game with nearly 50 million players. With a significant community, Catizen is set to host the Bombie airdrop on May 20, 2025, expected to be one of the largest token generation events of the year.
Source: link
@tonlines
Insights on Crypto Developments
🚨 Important updates in the crypto sector:
1. Trump's Crypto Czar, David Sacks, hints at "important announcements" for digital assets soon.
2. KIP Protocol claims support for the LIBRA token by Argentina's president. Backed by Animoca Ventures and involved with the AI project *Open Campus*. Read more
3. Argentine President Mile clarifies his earlier tweet supporting a private startup, stating he lacked details at the time and has since deleted the post after further understanding. Read more
#Crypto#AI#VC#Animoca#Argentina#KIPProtocol#Trump#DigitalAssets#Milei#LIBRA#OpenCampus#Startup#Partnerships#Decentralization#Finance#Blockchain#Tech
🔥Blockchain Life 2024 — starts in a week!
The legendary Blockchain Life 2024 forum will be held in Dubai on October 22-23. 10,000+ participants will discuss strategies for earning on hot trends of autumn 2024.
🎙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
🎓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.
👤Why should you go?
✔️ You will learn how to make money on cryptocurrencies and #Web3, regardless of which direction the market is moving.
✔️ You will hear inside information about what to invest in this fall and what is better to sell.
✔️ Traditionally, #BlockchainLife discusses cryptocurrency trends on average six months before they enter the masses.
✔️ All the industry leaders ( #Tether, #Tron, #TrustWallet, #Ledger, etc.) are coming to the forum, and you will be able to find the necessary contacts among the top community.
✔️ You will be able to communicate with the owners of cryptocurrencies that you have in your portfolio
📆When: October 22-23, 2024
📍Where: Festival Arena, Dubai, UAE
Registration:blockchain-life.com
You still can buy a ticket with 🛍 discount from our channel using the promo code: TONEVENTS
#TON#BTC#ETH#SOL#crypto#forum#networking
🪙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