Что делать если нужно поставить какую-то 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
We all are one.
The sun, the moon and the earth are one (once),
But in the time they all seperated,
Being and living far away,
But they all are one.
We born on different places,
We raised in different cities,
We studied in different institutions,
But we all are on one stage. i.e,, Life.
Our handwriting may be different
But the alphabet are one,
Pens may be different,
But the ink is same,
Books may be different,
But the knowledge is eternal.
We all are separated ,
by life,
by paths,
By careers,
But our hearts are together,
and We all are one.
Our tastes,
our preferences,
our perspectives,
our thinking,
May be different but,
We all are one.
S NAVEEN
#poetry#SN#review
Seperation lives
The life of human started from seperation,
Separation from the ocean,
Separation from the species, and
Separation from the womb of mother.
Nature is separated,
Oceans are separated,
Continents are separated, and so,
The nations emerged seperately.
Separation is the birth of new life,
Separation leads to innovation,
Separation is the worse, but
Separation is the nature.
When two persons seperates,
The heart brokes, and
Mind resides in despair, and
Life teaches the valuable lessons.
Even the origin of universe,
Started from the separation,
From one to one and another,
Separation is an unending process.
Separation begins with despair and,
End with hope.
Separation is natural and,
Separation is permanent.
PS: ignore grammatical mistakes
S NAVEEN
10-07-2022
#poetry#SN#review
Deadly hunger
I have seen that one person begged,
Other person insulted his fellow being,
And the other person cried for his condition.
I have seen people selling their body,
I have seen one died, and
Other inviting the death.
I have seen one in misery,
Other fighting to end the misery,
And other mentally broke down in it.
I have seen the starvation of children,
I have seen men working hard, and
The old seeking for help.
I have seen false promises of politicians,
Flop ideas of business men,
Which told to end hunger and poverty.
Hunger, a six letters word,
Running the world with ruthless,
Where it has no permanent end.
S NAVEEN
23-06-2022
#poetry#SN#review
These nights
I hope sleep find its way,
Before my thoughts destroy me,
Exhausted feelings and emotions will make,
These nights more scary.
There was a nights in moon light,
where we are sleeping peacefully,
Why this artificial lights making,
These nights more terrible.
In the war of mind and heart,
Sleep is just a pawn,
Where heart and mind will never win the war,but
These nights witness as spectators.
S NAVEEN
#poetry#SN#review
Sky...
You are the blue,
You are the light,
You are the carrier of clouds.
You have been witnessing the war,
You have been witnessing the peace,
You have been witnessing the love,
You have been witnessing the world. (From Alpha)
You have seen the tragedy,
You have seen the lives,
You have seen the nature,
You are the meaning of eternal.
You took the poison,
You took the pollution,
Yet, you never changed your colour. (like politicians)
You are the miniature of the oceans.
You are the floating blue ocean and
wonder of the universe.
S NAVEEN
#poetry#SN#review
On Long distance relationship.
Distance is just a word,
When two hearts beat together,
Kilometres and miles are just measurements,
When two souls turns into one.
There may be lack of communication,
But two minds will think the same.
Distance and lack of communication is;
Just for those, who thinks they are separate,
Not for those, who thinks they are together.
Love never thinks it way in impossibilities,
It always find it ways in possibilities.
S. NAVEEN
#poetry#SN#review
Eternal Love
I just opened the eyes,
Aloud tears filled the room,
That's the first time that,
I saw true form of love,
My Mother.
She hugged and kissed me,
With happiness and tears in her eyes,
That's the selfless love.
I have never seen 'her' before,
But I felt her touch in womb,
Her hands touched me,
Her womb protected me.
I have seen her and cried,
Her gentleness in heart,
Her intangible love,
Is the pinnacle in the whole world.
S NAVEEN
#poetry#SN#review