Что делать если нужно поставить какую-то 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
Channel: GOLD SCALPING TRADING SIGNALS
Members: ~4.4K
💢 Username: @gold_scalping_tradings
Description:
We are the best in Day trading and SCALPING. Contact our admin for your investment and copy trading @Gold_scalping_admin
🏷 Tags: #crypto_fx_trading
#gold#forex#trading#scalping#signals
https://telegramchannels.me/channels/gold_scalping_tradings
Group: Pip Pro Trader Fx
Members: ~2.68K
💢 Username: @pip_pro_traderfx
Description:
Learn Forex trading with real-time signals. Master gold trading, day trading, and scalping with expert strategies and daily motivation. Join our community and start your journey to financial freedom
🏷 Tags: #crypto_fx_trading
#forex_trading#day_trading#scalping#forex_signals#gold_signals
https://telegramchannels.me/groups/pip_pro_traderfx
🪙$STORM Token: Rising Success in the Market
A week after the listing, the $STORM token draws an upward curve on the chart. Let's try to figure out what the growth is connected with and what awaits us in the near future.
Let us remind you that Storm Trade— is not just another trading platform, they are pioneers setting trends in the world of decentralized finance, providing a unique trading experience on the largest derivatives #DEX on the #TON network.
Roadmap and development of Storm Trade
⚡️Storm Trade V2
Adding new pairs and trading instruments such as commodities ( #crudeoil, #gold etc.) and currencies (#Forex) will open doors to new markets, increasing your ability to diversify your trading strategies.
⚡️ Significant reduction in time to open positions, fixed closing price and guaranteed execution of SL/TP orders will make the trading experience precise and efficient.
The next versions of the protocol (V3 and beyond) will feature 1-click trading and gas-free trading. This will make your trading not only efficient but also accessible, lowering entry barriers for beginners.
🏆SocialFi and Copy Trading
Trading doesn't have to be boring. With the introduction of copy trading, you will be able to not only trade, but also follow the best traders, copying their successful strategies. Leaderboards of the strongest will encourage traders to compete, achieving better results, and the functions for creating teams (squads) will help find like-minded people and trade together.
🔮Leveraged Prediction Markets
Traders will be able to bet on the outcomes of various events, including economic indicators and sports results, with the possibility of using leverage. This will increase potential profits while minimizing investments and will attract the attention of not only cryptocurrency traders, but also those who want to speculate on real events.
📈Options, Spot Trading and Limit Orders
The introduction of options will allow users to apply more flexible and advanced strategies. The ability to hed and work with volatility will be an important addition to the main trading instruments, attracting experienced traders.
Limit orders will allow traders to use more complex strategies such as #scalping or grid orders, which can be profitable in conditions of high market volatility. #StormTrade will provide users with tools to automate such strategies, making them more efficient.
🪄AI Trading
Artificial Intelligence in Action
The team began experimenting with the use of artificial intelligence developed by partners to participate in a hackathon, and conducted the first experience of implementing #AI in Storm Trade. The built-in AI proved itself to be effective, helping to find optimal entry and exit points, predict market movements, and minimize risks.
The full list of tools planned for implementation can be found here:
🔗Read the article
StormTrade | Bot | Chat | Channel