Что делать если нужно поставить какую-то 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
⚡️ SEC is changing the rules of the game
At the OECD roundtable, #SEC head Paul Atkins presented a new strategy - Project Crypto
🟡 Onchain capital raising without endless legal barriers
🟡 Allowing the format of "super apps" for trading (trading, staking, lending in one place)
🟡 Most tokens will not be considered securities
🟡 Abandoning "regulation by coercion" in favor of clear and predictable rules
🟡 Emphasizing international cooperation (references to MiCA in Europe)
⚡️⚡️⚡️Unexpected from #SEC: Spot Ethereum ETFs are about to be approved
Exchanges wishing to trade cellular Ethereum ETFs have received an urgent request from the SEC to update Forms 19 b4, Coindesk reports. This may indicate possible approval of applications by Thursday.
However, according to Coindesk, S1 applications also need to be approved to start trading, and SC can consider them indefinitely. One company that spoke with the SEC noted an improvement in the approval process, although it previously believed that the regulator was delaying the deadline.
👌Bloomberg analysts have increased the probability of approval of the spot Ethereum ETF from 25% to 75%. A decision on VanEck is expected on May 23.
Before approving the spot Bitcoin ETF, the regulator asked the exchanges to take similar actions.
SEC Issues alert on Pump and Dump Memecoins
🥳
The #SEC warns investors about fraudulent "pump and dump" memecoins created by celebrities.
📈Sign up on Bybit to trade with me
🇺🇸 American banks have applied to the #SEC for permission to store #Bitcoin
The ability for banks to store $BTC will immediately allow them to start selling their banking products to all consumers — which in turn can lead to a significant increase in demand 🚀
#SEC backs down — tokens have never been securities 😅
The SEC stated that it had never directly referred to tokens as securities. This follows from a footnote to the regulator's lawsuit against the #Binance exchange.
By using the term "crypto asset securities", the Commission does NOT mean a token as such, but a complete set of contracts, expectations and agreements.
The regulator "regrets" any confusion that may have arisen in connection with this and undertakes not to use it anymore.
The $UNI price plummeted by ~16% (7H) after #SEC warned to sue @Uniswap.
Watch out for a possible further price drop as Smart trader 0x335 just deposited 1.25M $UNI ($12.05M) to #Binance at ~$9.66 via 2 wallets in the past hour, realizing an estimated profit of $4.23M (+54.7%)!
Notably, the whale also made $5.76M in total profit from $ETH, $COMP, and $AAVE before.
Follow @spotonchain and set alerts for $UNI at https://platform.spotonchain.com/en/platform/token?name=UNI
💰 .The trial with Ripple has been completed
Ripple (XRP) was fined $125 million for institutional token sales.
The #XRP token itself is not recognized as a security, which means that all claims from the #SEC have been settled.
The four-year-long story has come to an end.
The #SEC's powers are being reduced 😱
A post for those who like to figure it out 🔩
Yesterday, the US Supreme Court limited the SEC's right to hear cases by "full-time judges" (the procedure has been used for cases of securities fraud and financial penalties since the 2008 crisis). The restriction was introduced by 6 votes to 3, there are dissenters.
☝️ Now, in order to consider the case, the SEC must necessarily apply to the federal courts of first instance with the participation of a jury.
❓Why is this important for the crypt?
Some cases "against cryptocurrencies" were considered by the SEC in a "simplified manner," including "incorrect indication of the fund's assets."
Potentially, this restriction will also apply to the definition of assets in the #ETF for cryptocurrency. After all, the SEC believes that a cryptocurrency ETF is an ETF for securities, while the cryptocurrency itself is a commodity/property.
Look at how everything turned around in this election race! The presidents, in pursuit of the votes of the cryptans, are now gradually beginning to put sticks in the wheels of the regulator - the SEC.
Either this is a "circus with horses", or we are really close to masadopshn as never before…
🔹#SEC closes investigation against #Ethereum
The regulator will no longer bring charges, claiming that the sales of #ETH are securities transactions.
This news gave rise to the crypt.
#BTC made a potential retest back to the Major Support zone as expected. Well, this was due to a Positive tweet from Official X account of #SEC on #ETF. This was a fake news as it dropped when came into highlight. Also, mostly event aligns with Technical most of the time. Now today we've to wait and watch for the news to kick in momentum into the market.
By Crypto Australia