Что делать если нужно поставить какую-то 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
Are you eligiblen't for the $ZK airdrop?
We got you $KZ. 👉https://kzco.in
Users engaged in activities on #zkSync are airdropped $KZ points, which are claimable and will be convertible to $██.
👀 $ZK is available on the TokenPocket wallet!
From now on, you can easily store, trade, and track the real-time $ZK price on the TokenPocket wallet.
🌵If you haven't claimed your $ZK yet, please remember to claim it through the 'Airdrop Zone' on TokenPocket's Discover page. #zksync
📺🪂Get Free $GRVT token #Airdrop🪂
GRVT Dex Based on #zkSync Era 🕊
🎁Every new users who signup will get 10 GRVT points which can be convertible into Tokens after Launch
1🔴 Signup here: https://grvt.io/exchange/sign-up?ref=6HJUGJ3
🆓 Use this referral code to get 10 GRVT: 6HJUGJ3
🆕 EraLend now fully supports TokenPocket login, and EraLend
is also listed on TokenPocket zkSync Era Hot DApp List!
EraLend is the first native lending protocol on zkSync.
🔥You can access EraLend with your TokenPocket wallet and experience the Lending Protocol on zksync!
#TokenPocket#zkSyncEra#zkSync
Quoted TokenPocket_TP : 📣 Only 3 days left!
Don’t hesitate to complete the tasks and get your #Tinykingdom Starter packs!
🔥Available for 2 #zkSync tinyworldgamefi seasons!#GameFi
👇👇👇
【Details】https://twitter.com/TokenPocket_TP/status/1690542277058600960
【Powered By】Crypto Box
.#TinyWorld Giveaway Winner List
🔥Big Congrats to the winners! Thank you for joining us!
🏆 Winner List ⬇️⬇️
https://docs.google.com/document/d/1-8g_XO29u2Q0cJAwn7pTLNIWXo5tHdmiAn1ZrCWc8aU/edit
🔥Claim your tinyworldgamefi Kingdom #zkSync Starter Packs on TinyWorld Email Box, start your zksync #GameFi journey at once!
⏰ The rewards will be distributed within this week.
If you have any questions, you can join TokenPocket's Telegram to get more info, https://t.me/tokenPocket_en
https://twitter.com/TokenPocket_TP/status/1689171017674162176
【Details】https://twitter.com/TokenPocket_TP/status/1692121379540447389
【Powered By】Crypto Box
📋The sensational #LayerZero (ZRO) is trading at $ 3.05 and the current circulation of unlocked coins is only $ 770 million, the total capitalization is also small - $ 3 billion, which is 2-3 times less than Aptos or SUI. #zkSync (ZK) has a similar picture, the total capitalization is even more than ZRO by 900 million.
🧐It looks very modest, I think few people predicted this. Looking at this picture, you start to worry about the rest of the altos with large capitalization. And looking at the small ones, you also think about it. After this, is it possible to believe in a further correction of Chia (XCH)?
🥸Both projects are technologically advanced, but in different aspects. zkSync focuses on scaling and efficiency within a single blockchain (Ethereum) using advanced cryptographic techniques. LayerZero is aimed at improving the interaction between different blockchains, which is also an important task for the entire industry.
😎I think for #ZRO and #ZK you need to allocate a place in your portfolio, lay a theoretical descent lower by 30-50% and start buying a ladder from the current level, of course we are talking about spot. That is, to allow a speculative decrease in ZRO to $ 2.1 and ZK to $ 0.13 due to a speculative decrease and liquidation of longs on futures. But you need to understand that the current price is already very attractive, you need to partially buy now.
#Giveaway Get your Tiny Kingdom #zkSync Starter Packs!
🎁30 x #Tinykingdom Starter packs (worth $1050) for TokenPocket users. Complete the tasks and claim the OAT🔻🔻
https://galxe.com/TokenPocket/campaign/GCqxpUjyyb
💥Start playing the #game immediately with no upfront cost!
Play ▶️https://app.tinyworlds.io/game/dashboard
💁🏻♂️Make sure the current wallet address is the same as the
zkSync Era wallet address and you’ve downloaded and imported your wallet in TokenPocket!
🚀 zkSync to Unlock Significant Number of Tokens on April 17
zkSync is set to unlock approximately 17.314 million tokens on April 17 at 0:00 UTC+8. According to ChainCatcher, this release is part of the platform's ongoing token management strategy. The unlocked tokens are valued at around $2.66 million. This development is closely watched by market participants as it may influence the token's market dynamics.
#zkSync#TokenUnlock#Cryptocurrency#Blockchain#MarketUpdate#CryptoNews#ZK
🎉 Join the @NvirWorld X @zealy_io Airdrop Event! 🎉
🏆 Win a share of 2,000 USDT in Airdrops for 100 lucky winners!
✅ Complete tasks to become part of our program.
✅ Stay active and support our community.
✅ We will have 100 top winners!
👇 Join now and don't miss out! 👇
https://zealy.io/c/nvirworld/questboard
⏰ Ends on September 27th.
#Airdrops#BSC#NvirWorld#NVIR#ETHGATE Blockchain #Arbitrum#Solana $XRP $ZIG #zkSync#Binance $tip @tipcoineth#tip
Funding Rounds and Crypto Insights
🔍Funding Highlights:
1️⃣Equator - $5M round focused on climate transition in Sub-Saharan Africa.
2️⃣Jentic Technology - $4.14M round for AI integration with APIs.
3️⃣Flint - $2M round inspired by nature.
4️⃣Neovici - $997.05K round for AI in finance.
5️⃣Sushidata - $150K round for user feedback analysis across platforms.
✨Michael Saylor plans to burn his Bitcoin after death, raising concerns among investors.
📈Holdstation sees over $10M in trading volume on ZKSync, expanding to Berachain.
📊Deribit reports strong BTC performance and ETF inflows.
Full reports: ZKSync, Deribit Insights
#Funding#Equator#Jentic#Flint#Neovici#Sushidata#MichaelSaylor#Bitcoin#BTC#Crypto#Trading#AI#Finance#ETFs#ZKSync#Innovation#Investors#Tech#VC