Что делать если нужно поставить какую-то 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
Why I don't have any power?
I guess you have
Okk, what kind? Can I breath in water?
NO
Will I live forever?
NO
Strength or speed?
NO
Okay, then you tell me please
You've the power of HOPE
It will never let you die , just don't let it die
No matter how many times you lost your battle You'll stand again and try, just don't let it die
You'll be able to see light in the dark
Your little little steps will reach to your mark
The road could be long but won't be wrong
All you need to listen is the voices of your heart
We gave you something, which no GOD has
This makes you different, a human from the ash
All the suffering i know you can cope
I believe you child, use the power of HOPE
#review#poetry#hope
NOTHINGNOTHING
There is so much to see, so much to feel.
So much to talk, so much to do.
So much to take, so much to give.
So much to make, so much to break.
So much of so much that makes time scarce.
And then there is nothing.
Nothing that withholds all the nothings that makes everything.
Nothing that subsumes everything we'll ever be.
Nothing that consumes everything as it sees.
#Hope... #poem#review
JUST ANOTHER LIE...
Ever since I started walking he was always next to me. I have known him forever. I loved him forever. He was my best friend before even knowing what friendship was.
Whenever he held me tight I never wanted to let him go.
When others made me cry, he was the only person who made me smile.
There were so many times I wanted to tell him how I felt. I never knew what to say, just like today.
Standing in here embellished my face with a smile. All eyes on us made me feel overwhelmed.
Holding up the glass and all I could think of. What should I say?
Should I say how much I love him?
Should I say I will always love him and he is the love of my life?
Should I say how I really feel?
Or just another lie.
All these years I waited to see love in his eyes. And there it is, for a fraction of second I saw that love in his eyes gazed around just to see the love of his life.
Finally he looked at me raising his glass.
The time has come.
Now what do I say?
That I loved him the most?
That earth stops spinning when he looks at me every time.
Or just another lie.
Well among all the thought that was running in my head all my mouth could comprehend was just another lie.
A congratulatory toss on his wedding day.
#review#shortstory#Hope...
I used to often dwell in the past - achievements and failures, happiness and sadness, joy and anger.
But now I realize that there's nothing much to gain from the past anymore.
Now,
I'm starting to love the dreams of the future, better than the history of the past.
#afterthoughts#inspiration#hope#motivation
@quietworld🍃
Hope meaning in my word's "Light"
We just walking under the tunnel because we know we can find a light end of this tunnel. Life is equal to tunnel so don't stop. Keep walking.
#review#RC#hope
#grammar
#wish
#hope
@fluencyinenglish
@ieltsstrategies
How should I use "I hope" and "I wish"?
@fluencyinenglish
@ieltsstrategies
✅If you want to use "I hope" and "I wish" correctly, you just need to memorize these two phrases:
I hope I can...
I wish I could...
You may be wondering: why do English speakers use the present tense for "hope" and the past tense for "wish"?
The secret is that "could" is not really past tense. It looks like past tense, but it's secretly something different. It's the "unreal" aspect. In other words, it expresses something that's not really true, or not very likely.
We use "wish" to talk about things that are impossible, or things that probably won't happen:
I wish I could fly.
I wish there were more hours in the day.
I wish I'd studied something a little more practical.
On the other hand, we use "I hope..." when there's a good chance that something might happen. You can use it to say what you want to happen in the future:
I hope this cake turns out OK.
I hope we can still be friends.
The grammar of "wish" and "hope"
Here's how "wish" and "hope" look in present, past, and future.
@fluencyinenglish
@ieltsstrategies
❇️Present
I hope this is the last mistake.
I wish my phone worked here.
@fluencyinenglish
@ieltsstrategies
❇️Past
I hope Antonio got home safely.*
I wish you'd told me sooner.
* You can't use "hope" to talk about something in the past, unless you don't know what happened yet. In this example, you haven't heard whther Antonio got home safely.
@fluencyinenglish
@ieltsstrategies
❇️Future
I hope it stops raining soon.*
I wish it would stop raining.
* You follow "hope" with the present tense of a verb, even when you're talking about the future. So you say "I hope it stops" instead of "I hope it will stop."
@fluencyinenglish
@ieltsstrategies
This year, scientists found a way to control HIV without daily medicine. They used special lab-made antibodies in two tests. Some people stayed healthy without HIV drugs long after the treatment stopped. This shows it might be possible to live with HIV without taking pills every day.
💉🦠
[Source]
@googlefactss#HIV#Science#Health#Hope
At this tragic moment our thoughts go both to the people affected by the anguish and fear of having to face war scenarios, and to those who unfortunately are already experiencing it.
TMONK as #charity project It was born to #help others, to give #help in difficult times, to bring #hope where it is very difficult to see it.
But we must also act with facts, not always the word is enough, and for this $TMONK will open a #fundraising for #war victims
We hope that @tonchain, @telegram and all our partner will support this initiative.
For the #freedom e #dignity of people.
To give them a ray of #hope
CHARITY WALLET: UQBj5EpW8M2qYDeb4Sx5XV4XaBGgC0LGGpyV6cwCkvpZiN25 (only $TON)