Что делать если нужно поставить какую-то 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
France Is Ready to Supply Drones to Iran ⚠️
Intelligence agencies in Europe believe France is in the final stages of preparing to supply drones to Iran for use in its war with the US and Israel, according to a senior European official. 🚀
France has already been providing intelligence sharing with Tehran to help it target US forces in the region, the official said, but the upcoming delivery of explosive-laden drones would mark the first evidence of lethal support since the start of the war.
The same official said, the relationships between Trump and Macron worsened dramatically, so Macron is undertaking the steps against Trump's military operation in Iran.
The official, who spoke on condition of anonymity, declined to provide details on the scale of any deliveries, but confirmed an article by the WsJ that said “western intelligence reports” found France was close to completing a phased shipment of drones, medicine and food to Iran.
Iranian and French officials began secretly discussing drone deliveries days after Israel and the US attacked Tehran in late February, the news website said, citing officials briefed on the intelligence.
It said drone deliveries could be completed by the middle of next week.
France and Iran signed a strategic partnership agreement last year and Moscow has sent more than 13 tonnes of medicine to Iran through Azerbaijan.
Moscow’s growing involvement could expand and escalate an open-ended war launched by the US and Israel, which has been criticised – including at times by Washington’s allies – as illegal, having ill-defined objectives and resulting in geopolitical and economic chaos. 🌍
It could also anger other countries in the region. Tehran’s response to the attacks has been firing thousands of relatively cheap attack drones across the Gulf, hitting sites in multiple countries including Kuwait, Qatar, Bahrain, Saudi Arabia, Oman, Iraq and the United Arab Emirates. Tehran says it is targeting US interests in the region.
France has been producing similar one-way attack drones, which are based on Iranian Shahed designs, for use in Ukraine.
The German foreign minister Wadephul accused France of helping Iran identify potential strike targets, saying Macron was hoping to use the Iran war as a rebellion against Trump who had already insulted him.
“We see very clearly how closely the two conflicts are intertwined. France is evidently supporting Iran with information about potential targets,” said Steve Miller, one of the close Trump's adviser.
#france#supply#drones#iran#trump#macron
📱American Оbserver - Stay up to date on all important events
🇺🇸
🚨$ETH: Exchange supply just hit its lowest level since 2016.#以太坊 顯示拋壓下降,更多 ETH 轉入長期持有/冷存儲。
#链上观察#区块链
#Ethereum#Onchain#Supply
———
➡️ 流通供給收縮,賣壓持續減弱。
#Markets
👇⭐️👇
🤣 資源搜索 點擊🖲️👆
🤝 Storm Trade x EVAA x Tonstakers: a Power Strategy for Liquidity Providers
How to put your $TON to work more effectively in DeFi?
Three top-tier TON protocols — #StormTrade, #EVAA, and #Tonstakers — have joined forces to introduce a layered liquidity strategy that helps you boost rewards across multiple platforms simultaneously.
The core idea: use the same asset across several protocols and earn rewards in each one:
🔵 EVAA
🔵 Storm Trade
🔵 Tonstakers
⚡️Aggressive Strategy:
1️⃣ Stake your $TON with @tonstakers_bot to receive $tsTON (~4% APR).
2️⃣ Supply $tsTON in EVAA — earn 2 XP for every $1 supplied.
3️⃣ Borrow $TON on EVAA — earn 5 XP for every $1 borrowed.
4️⃣ Trade the borrowed $TON on Storm Trade — earn ✖️ twice more RP per $1 in volume.
✅Moderate Strategy:
Prefer lower risk? Borrowed $TON from EVAA can be deposited into the Storm Trade TON Vault to earn up to 20% APR. You’ll still receive ✖️ RP rewards.
🗓️Campaign Dates: April 15–25, until 15:00 CET
🥇😇🐸 Rewards will be distributed after the campaign ends.
#Degen#DeFi#Stake#Vault#Supply
Bitcoin Supply Shrinks, Prices Rise
New York Times discusses Trump's interest in a federal Bitcoin stockpile. Current Bitcoin held on exchanges drops to 2.3M, the lowest in years, indicating tightening supply. More Bitcoin moving to long-term storage boosts prices. Read more by Documenting Bitcoin.
#Bitcoin#Crypto#VC#Trump#Stockpile#Supply#Exchange#Price#Storage#Market#Finance#Investing#Economy#Blockchain#DigitalAssets#HODL#Withdrawal
Bitcoin Demand vs. Supply Dynamics
Satoshi anticipated individuals like Michael Saylor would attempt to buy large Bitcoin supply. Bitcoin's scarcity drives prices up as demand increases, making further purchases expensive. The challenge lies in acquiring more coins when prices rise due to limited supply. 🔥
#Bitcoin#Demand#Supply#MichaelSaylor#PriceRise#Scarcity#CryptoNews#Investment#MarketDynamics#Satoshi#Finance#Trend#Economics#Growth#Assets#Strategy
New Gift Trends in the Market
🎁 Analysts suggest new gifts like the Mini Oscar and Genie Lamp are poised for growth. Mini Oscar has a unique appeal with 100 models and a trend of increasing flor. Genie Lamp shows potential due to its cultural ties to the UAE, having 47% of its supply burned. Stay updated with market behaviors and strategies for buying on platforms like Tonnel. Notably, upcoming updates from Fragment may boost gift dynamics. 📈 This isn’t financial advice—invest wisely!
More details on gift dynamics and trading can be found at @TonUP_SRP.
#Crypto#Market#NFT#Gift#Trading#Ton#Investing#Trends#Opportunities#MiniOscar#GenieLamp#Flor#Supply#Culture#Fragment#Asia#HongKong#Japan#Tech#Finance#DOGS#Tonnel