Что делать если нужно поставить какую-то 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
DAOLama x CapsGame: Launch of 'Follow the Lama' Season
#DAOLama#CapsGame
The DAOLama NFT Lending (@daolama) channel announces its collaboration with CapsGame for the launch of the 'Follow the Lama' season. Players can now use DIAMOND chips as collateral to gain liquidity on the DAOLama App. The new season features exclusive tasks, a leaderboard, and rewards that include converting lama points into tickets for valuable in-game items.
Source: link
@tonlines
👊Fatality Package is live
The arena burns with fire and lava – the atmosphere of an epic battle returns with the new ❤️CapsGame collection!
🔥 Total supply – 690,000 caps
🔥 Available in all packs: from Common to Legend
🔥 Each cap is a piece of the legendary universe, ready to become a weapon in your collection
Collect, trade, and fight – the collection is already waiting for you!
#CapsGame#TON#NFT#GameFi
🥴Whoaa! Chip utility is live, and farming has officially begun!
Astrologers have announced a month of major updates in #CapsGame. Did you think that chips were just for fun? No, they are not. Now chips can be sent to ❇️ staking and receive CapsGame tokens for them.
❤️$СG Token
🟣 The first phase of farming starts today and will last 10 weeks, during which we will distribute 5% of the total token supply.
🟣 Starting today, 30% of purchases will be sent to the liquidity pool at capsgame-liquidity.ton.
🟣 This is just the beginning, there will be a lot of news and updates in the game over the next 10 weeks. Don't miss out!
📝How does staking work?
Where the profile used to be, now lives a new beast called "Token". Let's figure out what that means:
➡️ You have 9 slots available for staking: 6 slots for chips of any collections, and 3 slots only for certain collections, which will change once a week, at 00:00 Moscow time on Wednesdays.
➡️ Each staked token generates a certain amount of tokens per hour (starting with EPIC).
➡️ The higher the grade and popularity of the feature, the higher the generation speed.
➡️ The higher the grade of the chip collection that is staked, the greater the bonus to the generation speed!
Still confused? Hit the wiki for the full breakdown
Game | Wiki | Chat | NFT collection
#CapsGame#TON#NFT#GameFi
Festival season with Ton Festival and CapsGame!
Our friends from ❤️CapsGame and
🔠TON Festival decided to join forces and launch a new season! A festive atmosphere, fresh activities, and, of course, a bunch of surprises — all this is already here!
What's ahead?
⚫️6 Cool Chips for Your Collection
⚫️ Huge edition — 20,000 chips
⚫️ Leaderboards and festival activities right in the game!
How to Earn you Tent Points 🏕
⚫️ Completing dailies: 10
⚫️ Mint of any chip: 50
⚫️ Chip Madness Round Completion: 5 (no repeats)
⚫️ Upgrade your chips to Legend+ and higher — the cooler the chip, the more points!
🏅Prize fund — tickets🎫 giving cool bonuses and exclusive items await those who collect the most points at the end of the season.
🗓️The final day of the event is March 27. The store opens on March 28th — exchange tickets for cool prizes!
🫶Become a part of the main event of the year!
#CapsGame#TONFest#Web3#TON
CapsGameon💎TON Community
The game was mentioned on the official TON channel, perhaps a hint that it is a future participant of the League.
CapsGame combines nostalgic gaming with innovative Web3 technologies, incentivizing active participation in the TON ecosystem through NFT trading. Players can earn rewards and profits from trading and upgrading their NFTs.
The game offers a PvP mode for those who like to take risks and bet their NFTs on the outcome of a battle with other players, as well as a safe PvE mode in which the player trains by playing with bots. CapsGame also encourages engagement and competition through rankings and quests.
And right now there is a new contest in BroBot together with #CapsGame in which you can get a unique SBT BroBot CapsGame and other prizes absolutely free.
☀️Complete tasks and get SBT!
#NFT#SBT#TON#BroBot
🛋Ease In, Get Cozy, Enjoy
❤️CapsGame has become even more cozy — the team has updated the main screen! Now the mini-app has become even more cozy and addictive. No more associations with clickers — maximum nostalgia for the OG game Chupa Caps, so launch the game and immerse yourself in the atmosphere of childhood.
Collect your favorite chips and turn valuable items into NFTs, which are already traded on #Getgems.
Game | Wiki | Chat | NFT collection
#CapsGame#TON#NFT#GameFi
💎CapsGame is launched! Caps are back from the 90s!
🧑💻CapsGame finished beta testing, fixed bugs and improved the app itself. Added in-game purchases for stars, plans to add support for payment in $TON and new activities based on the rating table
👌 The public release introduced a leaderboard that will be formed based on unique player collections. This means that each chip you collect will earn you points. By upgrading chips or completing collections, you will earn additional points. Each chip will be unique, with its own number, and collections will be strictly limited. More details.
🙂 For active participants of the beta test, special rewards were provided, which you can read about in this post.
Play in our Yard and start collecting rare chips, let's try to rise in the district rating together!😎
1️⃣Go to bot
2️⃣ Come into our yard
3️⃣ Play and win!
#CapsGame#TON#NFT#GameFi#ChildhoodComingBack