Что делать если нужно поставить какую-то 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
🇺🇸 The U.S Government moved 97.34 $BTC ($8.52M) and 884.3 $ETH ($1.78M) to new wallets in the past 8 hours!
These funds were confiscated from Sae-Heng, a person involved in confidence scams.
Currently, the #USGovernment still holds 198.4K $BTC ($17.3B) and 58K $ETH ($116M).
Follow @spotonchain for more updates at https://x.com/spotonchain/status/1905438552164630944
🚨[BREAKING] The US 🇺🇸 Government has received approval to sell 69,370 $BTC (~$6.5B) seized from Silk Road!
Note that previous sales did not directly impact the price, as they were done via OTC, but market panic often caused temporary drops.
Currently, the US Government holds around 197K $BTC ($18.6B).
Follow @spotonchain and track the #USGovernment now!
👉 Details: https://x.com/spotonchain/status/1877182579906068970
💰 The #Bitcoin OG is currently sitting on another $22.6M unrealized profit from its $BTC short (10x).
• Size: 4,394.74 $BTC ($484M)
• Entry: $115,288.40
• Liquidation: $124,264.31
• Last added: 7 hours ago
Meanwhile, 2 hours ago, the #USGovernment moved 667.62 $BTC ($74.8M) from seized Potapenko/ Turogin funds into a new wallet. No further movement yet, but $BTC has dropped by $1,420 since.
Follow @spotonchain for more updates now!
https://x.com/spotonchain/status/1978053536865988992
🚨 The #USGovernment moved 19,800 $BTC ($1.92B) out 8 hours ago, of which 10,000 $BTC ($962.9M) were sent to #Coinbase.
So far in 2024, the US government has transferred a total of 25,999 $BTC (now: $2.49B) to Coinbase. However, these transfers appear to be custody actions rather than sales.
Currently, the US government still holds approximately 183,850 $BTC ($17.57B) across various known addresses.
Follow @spotonchain and check out more details at https://x.com/spotonchain/status/1863763869220647172
The US Government moved another 3,940 $BTC ($241M) to #Coinbase Prime ~9 hours ago.
Their last move was sending 2K $BTC ($131M) to Coinbase Prime on Apr 3, 2024 but it did not directly affect the BTC spot price.
Currently, the US Government holds around 213.5K $BTC ($13B).
Follow @spotonchain and monitor the #USGovernment entity via https://platform.spotonchain.ai/en/platform/entity/188
The #USGovernment transferred 15,940 $BTC($966.4M) to #CoinbasePrime in three transactions this year.
Within three days of the first two transfers, the price of $BTC both dropped by ~5%.
https://platform.arkhamintelligence.com/explorer/tx/b614dd2e0fa06d776ee4d45973fab5ceb6e2dfebfb84e5f7bd45ef0975455240
https://platform.arkhamintelligence.com/explorer/tx/0f3f9a7c01d85c5747a3ae6cc9621cc30360390c4b681c1f95573e6bbcffed4f
https://platform.arkhamintelligence.com/explorer/tx/a224c1658e4e4c1c0480312aea6c6102dbd5ec912810c799998a4d2f00741b0d
The #USGovernment Silk Road address transferred 10K $BTC($594M) to #CoinbasePrime 2 hours ago!
The #USGovernment currently holds 203,239 $BTC($12.05B).
The US Government deposited another 58.74 $BTC ($3.96M) to #CoinbasePrime 7 hours ago.
So far in 2024, the US government has moved out 6,261 $BTC at an avg price of $62,538 ($392M), mostly after the price rose in late Feb. Among those tokens, 5,999 $BTC ($376M) went to Coinbase.
The US government still holds 213K $BTC ($14.3B).
Follow @spotonchain and set alerts for the #USGovernment now via https://platform.spotonchain.ai/en/platform/entity/188
🚀 U.S. Government Budget Deficit Narrows in March
The U.S. government reported a budget deficit of $164 billion in March. According to Jin10, this figure was slightly higher than the anticipated deficit of $156.7 billion but showed a significant improvement from the previous month's deficit of $308 billion. The narrowing of the deficit indicates a positive shift in the government's fiscal position compared to earlier projections.
#USGovernment#BudgetDeficit#FiscalPolicy#Economy#March2026#GovernmentFinance#EconomicUpdate
🚀 CZ Accepts Prosecution as Consequence of Scale, Looks Forward Despite Fairness Doubts
Speaking on The Wolf of All Streets Podcast, Binance co-founder Changpeng Zhao (CZ) reflected on the fairness of his prosecution, drawing a parallel to the 1980s US War on Drugs — in which people received lengthy prison sentences for selling marijuana that is now legal in many states — to illustrate how legal standards shift over time. CZ said he believes Binance was the first major crypto platform targeted by the US government under the Biden administration because it was the largest, adding that he understands Senator Elizabeth Warren remains opposed to crypto. He characterized the question of fairness as subjective and said he does not dwell on it. "Is that fair or not? I don't think it matters that much," he said, adding that he is focused on looking forward and continuing to build.
#Binance#ChangpengZhao#Crypto#Cryptocurrency#Prosecution#Legal#USGovernment#ElizabethWarren#Blockchain#Regulation#BNB
Binance Hits 250M Users, Record Stats
Binance reports over 250 million registered users by year's end, a 47% increase. Platform processed 4.44M requests/second; VIP users up 116%, institutional users up 97%. Internal compliance team expanded to 650 experts. Read more
US government clear to liquidate 69,000 Bitcoins (valued at $6.5B) seized from Silk Road. This follows a promise by the new administration not to sell the Bitcoins. Read more
#Binance#Bitcoin#Crypto#Users#VIP#Institutional#Compliance#SilkRoad#Seizure#Finance#USGovernment#AnnualReport#MarketCap#Trading#Blockchain#Investments#Tech#DigitalCurrency#News