Что делать если нужно поставить какую-то 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
Guys @MyCoralApp NFTs, which BinanceLabs is an investor and supporter of, were recently minted for free. It currently has a price of around $2-3.
Coral has a phone and those who own it earn tokens.
The project will distribute a large portion of the total supply as an airdrop! I added it to my bag in case there might be a surprise for NFT owners.
floor went from $2 to $4 and is still cheap #nfa
See the collection : https://magiceden.io/collections/bsc/0x6dfbb01ecb7991366cd8acc4d18dcc67bbe345ba
🎁21,900 $DORA Airdrop on BNBCHAIN!
→https://zealy.io/cw/tokenpocket/questboard
*Exclusively for the community. No investment advice — just memecoin fun! #NFA
All Bonk-Ending Tokens Now Tradable on TokenPocket! 🎉
Trade ANY token that ends with 'bonk' on Solana —whether pre-launch or live—all in one place with TokenPocket’s Meme Mode! 🚀
#NFA
Pump with TokenPocket!
📱http://tp.xyz
💻http://swap.transit.finance
⚪️
🪙RUDY FL PRESALE LIVE AND ENDS IN AROUND few hours
🪪
✅
✅
🪪
⭐️Based team so keep a watch for your best entries. Dyor,Nfa.
Rudy is a legendary character based on a famous animated movie! He is an animal lover and passionate about exercise and investments. Now, Rudy lives on the Solana blockchain, becoming the purple mascot of the purple chain, Solana.
➡️Join Rudy on this exciting adventure in the world of cryptocurrencies and be part of his vibrant and fun community.
✅
Ⓜ️ CMC &
🦎CG fast track
✅ Marketing team
✅
✅Safu /
✅ Audit /
🪪KYC /
🪪Doxx
✅ LP locked 1 year
😊Pinksale Buy Link❤️👤🛡🔰:
https://www.pinksale.finance/solana/launchpad/2bX7RbeMygiiLDAp5MSTsZELQh7fqHQncApeRww2788k
🌐Website
✖️Twitter
✈️Telegram
#DYOR#NFA
Calling all Degens! 🗣️
A new Bot launches today:https://Palomabot.ai🐦🤖
Palomabot runs on the Paloma blockchain and partners with major AMMs and players to create MEV bots 🚫 that can trade momentum with no sandwich and with maximum backrun proits.
First Fast-Snipe Bots launching today:
* Paloma Momentum Bot
* CoinGecko Top 100 Bot
* Coingecko Newest $1MM Marketcaps Bot
* Curve Stop Loss and TWAP Bot
🤖 All Paloma Bots Snipe in 1-second and include limit orders to maximum profits & automatically exit positions.
💰 All money is returned to your wallets when positions close.
🔐 All money is custody by the Paloma blockchain so no rug-pull.
🔔 Telegram Alerts every hour for the hottest tokens to bot and profit.
🏆 All Bots transactions qualify for Paloma GRAIN token rewards.
Come degen with us and tell us what bots you want to use next!
https://Palomabot.ai🐦🤖
#NFA#DYOR
#DYOR#NFA
SCALE 🟡 APPARENTLY WELL STABILIZED, HAS A LOT OF POTENTIAL FOR GROWTH
if you think interesting, buy some bags!
DYOR • NFA
Mc now $27k
Tg : https://t.me/meta2k22bsc
Web : under construction
Chart : https://poocoin.app/tokens/0xb4039ec127cbab1e2bbd62aabf920aa57a900ecb
Ca : 0xb4039ec127cbab1e2bbd62aabf920aa57a900ecb
Ownership Renounced, Community based, Lp lock 1 month mudra
⚛️@TeamTanukiToken
Are you sick to death of reward tokens and useless projects lead by inexperienced development teams who constantly over promise and under deliver? Don't worry, we've got something super special to share with you😘
Our project, is lead by an experienced solidity & artificial intelligence development team. Here is just a snippet of what's instore;
• Initial simple contracts (Lottery, BNB fund, etc)
• Exchange listings
• Promotional Material for Future AI Contracts
• First AI Driven Contract
• Promotional material on “AutoTainment”
• Announcements of further AI products
• Extended DApp to track AI rewards
• Major exchange listings
• Advanced AI SC's
⚛️Marketing Statement
• Our first goal is to drive organic growth by being welcoming to newcomers into our ecosystem and community
• We like to market our unique attributes, we are a dog coin, but no one has done a raccoon dog before
🟣Telegram: http://t.me/TeamTanukiToken@TeamTanukiToken
🟣Website: http://tanukitoken.finance
#DYOR#NFA
#Advertisement#NFA
📣We call to our Investors!
📌 Just one step: From purchasing NFTs to creating and co-founding the bank of the future: TLVD Trusty Bank!
Closed listing by founders from May 9, 2024!
💎 Open sale of NFTs on the DeFi marketplace OpenSea begins on June 10, 2024!
UNION IS STRENGTH!
💬Contact:+372 5837 7377
🔍More information about the project:
✈️Telegram |⛵️Opensea |🌐Website
🔴Note:Please do your own research (DYOR) before joining to any project. Nothing in this post is financial advice (NFA).
✈️Business:@ProjectPromoters✅
#Advertisement
🚀 Don't miss out on the QUBY AI PRESALE! 🎮✨
Dive into the future of gaming and be part of the next big thing at http://QUBYAI.com🔥
Unlock exclusive benefits with CODE: QUBYAI2024 🔓
💬Note - Please do your own research (DYOR) before joining any presale, Invest only that part of your portfolio which you can afford to loose #NFA.
🔥Earn Hub is Now Live!
We’re excited to announce that Uniswap & PancakeSwap LP earnings are now officially live in the Earn section!
Simply provide liquidity to top token pairs and enjoy steady, stable returns on your assets.#NFA#DYOR
📱Discover -> Earn Section
https://x.com/TokenPocket_TP/status/2046770434952339884?s=20