Что делать если нужно поставить какую-то 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
Celebrate Thanksgiving with Getgems NFT
#Getgems#TON
Getgems NFT invites its community to share a holiday toast in their Holiday Drinks collection this Thanksgiving. Participants can win prizes such as Bling Binky and Money Pots by submitting heartfelt comments before November 29. Comments cost 0.5 TON and will be manually approved.
Source: link
@tonlines
Getgems NFT: Selling Subdomains on Getgems
#Getgems#TON
Getgems NFT now allows TON DNS domain holders to create and sell collections of third-level domains on the Getgems platform. Domain owners can set prices, manage their mini marketplaces, and earn royalties from subdomain transactions. The first such collection has been launched with the Lost Dogs project using the woof.ton domain.
Source: link
@tonlines
Getgems NFT: The Rise of Subdomains
#TON#Getgems
Getgems NFT discusses the introduction of subdomains on TON DNS. These subdomains offer a new way for domain holders and projects to monetize and create distinct ecosystems. More details on pricing and launch will be shared soon.
Source: link
@tonlines
⚡️Getgems NFT: Gift Fest Launches an Exciting Prize Hunt
#Telegram#Getgems
Getgems NFT announces the launch of Gift Fest, the largest gift festival on Telegram, featuring 100,000 gifts valued at $400,000. Participants can join by using the festival mini-app to play, merge gifts, and enter weekly raffles, culminating in a main raffle on December 29.
Source: link
@tonlines
New Telegram Gifts at Getgems
#Telegram#Getgems
Getgems has launched new Telegram Gifts which are now tradable with 0% fees. Users can transfer or purchase items like Bling Binkies, Money Pots, and Pretty Posies through the mini app or website.
Source: link
@tonlines
Getgems NFT: Easter Giveaway for Easter Domain Holders
#Telegram#Getgems
Getgems NFT is hosting a Flash Easter Giveaway for all holders of Easter-themed Getgems Domains and Telegram Usernames. Participants have a chance to win one of 20 Telegram Gifts totaling 100 TON. Winners will be announced on April 21.
Source: link
@tonlines
⚡️Getgems NFT: Black Friday Raffle Announced
#Getgems#NFT
The Getgems NFT channel has launched a Black Friday raffle with unique black-background gifts. From November 28 to November 30, users can enter by importing specific collectible items, such as Instant Ramens or Money Pots, via @gemsrelayer. Winners will receive special editions of these items.
Source: link
@tonlines
New Commenting Features on Getgems NFT
#Getgems#NFT
Getgems NFT introduces a new feature allowing users to make announcements and comments on NFT collections. Messages undergo moderation and can cost 0.5 to 10 TON, depending on the type of collection.
Source: link
@tonlines
Getgems NFT: Celebrate with Your Collector Wrap
#Getgems#NFT
Getgems NFT celebrates its three-year anniversary by offering users a unique Collector Wrap experience on TON. Connect your wallet to explore your NFT journey, claim a limited-edition anniversary SBT, and create a custom avatar.
Source: link
@tonlines
Getgems NFT: Sticker Digest Unveiled
#TON#Getgems#NFT
Getgems NFT introduces the Sticker Digest, highlighting notable developments in the TON sticker market. Key updates include the trading success of Goodies with over 250K TON, the pioneering Sticker Pack collections, and recent collaborations within the ecosystem. Enhanced browsing with new filters is now available.
Source: link
@tonlines
Getgems NFT: Marketplace Technical Issues
#Getgems#marketplace
The Getgems NFT marketplace is currently facing technical difficulties. However, the team is actively working to resolve the issues, and the website will be operational shortly.
Source: link
@tonlines