Что делать если нужно поставить какую-то 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
#SC/USDT analysis :
#SC is currently experiencing a bearish trend, making new lows. The price is rejecting from the 200 EMA resistance, indicating a potential continuation of the downtrend. The price is expected to decline further, testing the swing low level.
TF : 1H
Entry : $0.003495
Target : $0.003225
SL : $0.003636
The Freely Eagle...
Oops Conditons Applied.
what's life ?
Happines today in journey, there might be a Sad turn tomorrow.
Slipped if on that turn, just stand smile and move ahead.
That's what a life for me.
Oblivious about what's gonna happen fews day ahead, was enjoying his journey of life fully.
Like a free fierce Eagle at high above the Limit less sky.
Boards were going on, and he was blindfolded by the next twist waiting for him.
Someone was waiting to gain his love, in the mid of his boards.
who..? Some call her/him Danger, Dead end, life threatening, etc. But the Common name was
Cancer. Yes!!!
Was unknown about it and flying high in his journery of life. That turn came, was encountered too.
The moment he got to know. His wings were cut, and the Eagle was Caged.
All the dreams, aims, were shattered.
Like all his hopes were slaughtered.
Was Broken, hurted, and lost all the hopes.
Bacause, he was still and Fierce Eagle; but wiith conditions applied,
Who used to jump and Run, was now caged where he can just walk.
Who dreamt of many things, but was caged because he wasn't able to do of his wish,
But still, he dealed with it. Accepted the long life inprisonment of conditions applied.
If not the aims and dreams hi choosed, then
He went by making new dreams of he can.
If not sports and physical activities anymore
He went with Pen as his Passion.
Not the Happiness he used to dream of
But by happiness of bringing best of his words.
Yeah, it's my life like a caged bird now,
But if are caged by conditions or sort of same. It isn't mean you can't fly anymore.
Have faith and believe in you, and just have a take off with the cage of conditions with you above the Sky.
#sc
#review
#shortstory
@the_critpic_hunter
#SC/USDT analysis :
#Siacoin has broken out above the previous high with robust momentum and formed a higher high. The price is anticipated to sustain its bullish momentum and challenge new highs. Seek a pullback near the support zone to consider a long entry.
TF : 1H
Entry : $0.00465
Target : $0.00489
SL : $0.00451
#没用的外站信息
可能会被群友说是没用的外站信息,就合并到一起发了。
————
#SC#SecretCinema#站点公告
We have a new IRC channel that we actually control.
Server: irc.brokensphere.net:6697
Channel: #secretcinema
Use site nick especially if you require assistance.
Please don't use the #sc channel for assistance or help with your account as staff will no longer idle in this chat.
TLDR; SC 更换了 IRC 的域名。
————
#shazbat#站点公告
2024-02-25 - Webchat broken
As you might have noticed, the webchat is a bit broken. We are working on fixing it, but it might take some time.
If you want a good chat experience, join IRC (see the help pages).
TLDR; webchat 炸了,要聊天就来 IRC。
————
#ABN#站点免费
站免还剩 8 天+
————
#HeBits#站点免费
站免还剩 1 天+
————
#AcidLounge#站点公告
Hey all,
We had over 10 accounts that someone took advantage of maybe from stolen database from another site. These peeps have now lost there account.
So please don't use the same password as other sites maybe consider using Two Factor Authentication (2FA) which can be setup in your settings.
You can use an app like Authy
https://authy.com/what-is-2fa/
TLDR; 有人号被盗了,记得开 2FA。