Что делать если нужно поставить какую-то 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
🤔 Do you know how to use the phrase ‘bite the bullet’? Here’s an example sentence: “I decided to bite the bullet and start cleaning up after the party.” 🎉
💬 Can you write another example sentence?
EXTRA: to learn other useful expressions like this, click on our link in bio.
#LearnEnglish#Idioms#EnglishGrammar
🥗Salad? 🥕Carrots? 🍳Eggs? Do you like food as an adult that you hated when you were young? 🤮 Answer this grammar question – and then tell us all about it!
There's more about 'used' to on our website - just click the link in our bio! 👆👆👆
#Grammar#EnglishGrammar#LearnEnglish#English
📚First Conditional (Simple & Clear)
We use the first conditional to talk about real or possible situations in the present or future and their results.
🧩 Structure:
If + present simple, will + base verb
✅ If I pay attention in class, I will understand everything.
➡️ Real situation → real result.
#EnglishGrammar#Conditionals#LearnEnglish
👋 Learn how to use the present simple. Look at the images and complete the gap:
We _______ to school on Saturdays.
a. does not go
b. not go
c. don’t go
🤩 EXTRA: Click on our link in bio for more help with this tense.
#learnenglish#present#englishgrammar#englishtips
How to Learn a British Accent *Fast* - (Modern RP - ALL Vowels & Consonants!)
2023-03-23 by English with Lucy
#Grammar#EnglishGrammar#LearnEnglish
#YouTube#liked
Mastering Prepositions of Time: IN, ON, AT! ⏰
Do you ever get confused about which preposition to use when talking about time? You're not alone! Here is a quick cheat sheet to help you remember:
🎯 AT – for specific times (e.g., mealtimes, clock times, night, the weekend)
📅ON – for days and dates (e.g., Saturday, the 8th of September)
⏳IN – for longer periods (e.g., months, seasons, years, the morning)
Check out the infographic above for more examples!
Test your knowledge! Take the quick quiz below and see how much you've learned. Save this post for later, and forward it to a friend who is practicing their spoken English! 🔖
#LearnEnglish#EnglishGrammar#Prepositions#EnglishTips#ESL
🤯Oh no! We've all done it! But don't worry about your phone – can you answer this grammar question? We'll tell you the answer later! 😃
#pastsimple#englishgrammar#learnenglish#verbs#gapfill
There are lots of tag questions in English so which is the correct one? Look at the images and choose the correct tag question:
-
#learnenglish#questiontags#tagquestions#englishgrammar#englishtips#grammar
Difference Between “drop out” and “be dropped out”
Many people make this mistake:
❌ I was dropped out
This sentence is grammatically incorrect.
The correct structure is:
✅ I dropped out.
Meaning: I voluntarily left or withdrew from school/university.
Why “was dropped out” is wrong
“Drop out” is an intransitive verb.
It does not take an object, so it cannot be used in the passive voice.
❌ You cannot say:
I was dropped out of university.
Because dropping out is something you do yourself.
Correct Usage
If it was your decision:
I dropped out of university.
If it wasn’t your decision:
Use other verbs to express that:
I was expelled from university.
I was forced to leave university.
@fluencyinenglish
#EnglishGrammar#GrammarTips#DropOut#PassiveVoice#IntransitiveVerbs#IELTSGrammar#CommonMistakes#LearnEnglish#TEFL
Do you know how and when to use ‘in’, ‘on’ and ‘at’ to talk about time? ⏰
We normally use:
at – for specific times, such as mealtimes and clock times
on – with days and dates
in – for longer periods of time, such as months, seasons and years.
Save this post for later and don’t forget to share with a friend who loves learning English! 🔖
#LearnEnglish#EnglishGrammar#PrepositionsOfTime#InOnAt#GrammarTips#ESL#DailyEnglish
🛫 Advertising: @Advertise_on_Telegram