Что делать если нужно поставить какую-то 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
And as you fall and shatter.
Darling, think of the glory of your rise.
Think of the potential that lies.
You must gather all that lay scattered.
First on your knees
and then finally,
you stand on your feet.
#poetry#review#grace
On this day I conclude my body
and blend in God
to discover all those
whom I'd once lost!
I tasted every bit; every risk.
Blessings were showered abundantly;
every moment was a gift!
I cherish the smiles
that came into existence
because of my presence.
But now, my body has perished.
So don't you cry O My Beloved!
For I'll always be there,
in times of your happiness
even in times of despair!
I happily dive in my Creator
and bid adieu to His beautiful creations!
#review#grace#poetry
So rich and rare.
You hold me up
and blend me in your air.
I scent your breath,
your body!
I make you go insane
about your own-self
because I make you smell
like a wild rose
with gold petals!
You bring me close
and I spread kisses all over your body.
I peck your wrist,
you inhale me unnoticed!
You are privileged
to own me,
to keep me a secret,
for I am too precious to reveal
and too exotic to be concealed.
I'll be one of those perfume bottles
you'd love to keep
even after there's nothing left of me!
#grace#poetry#review
I seek motivation from within..
I hold the will to try
until my goal is fulfilled...!!
Afterall,
my despair got some faithful hope
and a chance to try once more....
When I look into the mirror,
I just don't see a person
burdened with numerous reasons
to fall for sadness
but an absolutely distinct soul
crawling around the space alone
to fetch happiness
in its own universe.
Just like the moon is scarred with craters
but still gentle with its coldness,
so is my universe scratched
with shooting stars
but holds galaxies of
unbearable positive energy
vibing with my soul!
#review#poetry#grace
Poems lay beneath my soul
patiently waiting to be unleashed
to devour every anxiety that runs through
and tie broken pieces
of my unloved heart
with lost yet enchanting phrases!
#poetry#review#grace
The roots of thy vices
shalt be slashed with dagger
of thy utmost morality
for tis but an illusion that
thou consider thyself a saint
dressed in extravagance!
#review#grace#quote
LILIES AND ROSE
I rushed to the store
and bought a bouquet of lilies and a red rose.
I was like an enthusiastic guitar,
gleeful; cheerful and indeed, grateful.
I decorated the house with fairy lights
and the rooms with crimson ribbons and balloons.
I smile through the memories
as how on our first Valentine's Day
I proposed her with a ring of platinum
and bouquet of lilies!
Lilies are her favourite
and so are mine!
I love my babe,
I love her pleasant smile!
I remember brushing her cheeks with white lilies
and did I tell you
that her name too, is Lily!
Must be wondering
why I bought a red rose!?
Let me tell you as I drive along.
An hour ago,
Lily gave birth to a baby girl,
who owns that velvet rose
and happiness of many more!
Perfect. I reached in time.
There's my family.
Mom, dad, in-laws.
Numerous smiles;
blooming happiness.
The moment, I wish I could pause!
I push the door
and see my lifelines;
my queen and my princess!
"Papa's here with lovely lilies
and Wow, a crimson rose! ", she says
as I kiss her forehead
and hand her the bouquet I bore.
I look at my precious child.
Her daddy-like features
and mom-like skin pinkish white!
The rose adorns my angel
as I rest her in my arms.
I gently peck her little fingers
and pray,
"let there be more love in the world my lord,
for I'm blessed with so much;
what more can I want! "
#ballad#review#grace