Что делать если нужно поставить какую-то 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
🇬🇧Popular English Idioms to Sound Like a Native Speaker
💣 BLEW ME AWAY:
✍🏽when something blows you away, you’re extremely impressed by it
🔺The exhibition just blew me away. I’d never seen so many beautiful paintings before.
☁️ BLOW SMOKE:
✍🏽to exaggerate or say things that aren’t true to make you seem better/ more knowledgeable than in reality
🔺I’m not blowing smoke. I have honestly read War and Peace by Tolstoy.
🐺 CRY WOLF:
✍🏽to call for help when you don’t need it
🔺Do you think Peter is in trouble or is he just crying wolf?
#sirjimmy
#teamjimmy
Show your true colours | show your true colors🎨
⌨Meaning
You show your true colours if you show what you're really like, or you reveal your true character.
🚦For example
👀Bob always acts like he's a strong, brave guy, but when the hurricane hit he showed his true colors. He was too scared to go check on old Mrs Flowers, our next-door neighbour.
👀The players showed their true colours when they came back from three goals down to win the match.
#sirjimmy
#teamjimmy
🇬🇧Popular English Idioms to Sound Like a Native Speaker
💣 BLEW ME AWAY:
✍🏽when something blows you away, you’re extremely impressed by it
🔺The exhibition just blew me away. I’d never seen so many beautiful paintings before.
☁️ BLOW SMOKE:
✍🏽to exaggerate or say things that aren’t true to make you seem better/ more knowledgeable than in reality
🔺I’m not blowing smoke. I have honestly read War and Peace by Tolstoy.
🐺 CRY WOLF:
✍🏽to call for help when you don’t need it
🔺Do you think Peter is in trouble or is he just crying wolf?
#sirjimmy
#teamjimmy
Show your true colours | show your true colors🎨
⌨Meaning
You show your true colours if you show what you're really like, or you reveal your true character.
🚦For example
👀Bob always acts like he's a strong, brave guy, but when the hurricane hit he showed his true colors. He was too scared to go check on old Mrs Flowers, our next-door neighbour.
👀The players showed their true colours when they came back from three goals down to win the match.
#sirjimmy
#teamjimmy
🌪️Negative Personality Idioms + Challenge 🎯
• 🗣️ A windbag – talks nonstop
• 🧊 A wet blanket – ruins the vibe
• 👀 A busybody / nosy parker – always in your business
• 👍 A yes-person – agrees with everything
• 😖 A pain in the neck – seriously annoying
• 🤯 A scatterbrain – forgetful and unfocused
• 👦 A mama’s boy – overly dependent
• 👐 A pushover – too easy to control
• 😈 A troublemaker – causes drama
• 💼 A social climber – status obsessed
• 🐢 A slowcoach – painfully slow
• 🗣️💬 A gossip – spreads rumors
• 🪨 A rolling stone – never settles
• 🛋️ A lazybones – super lazy
• 🎩 A stuffed shirt – too formal
• 😴 A bore – boring person
• 🧐 A snob – looks down on others
• 🚪 A gatecrasher – uninvited guest
• 🧠❌Narrow-minded – closed-off thinker
• 💔Hard-hearted –cold and cruel
• 🐖Pig-headed – stubborn AF
• 🐇Hare-brained – reckless thinker
💥Challenge:
Can you guess the idiom from the description? 🤔
1️⃣ Someone who ruins the fun at a party → ?
2️⃣ Someone who talks way too much → ?
3️⃣ Someone who is too easy to control → ?
💡 Tip: Try using one of these idioms in a sentence today! ✍️
#Idioms
#TeamJimmy
#SirJimmy
Stop and smell the roses 🌺
Meaning:
To relax; to take time out of one's busy schedule to enjoy or appreciate the beauty of life.
Example: 🌹
Slow down. Stop and smell the roses now and then.
#teamjimmy
#sirjimmy
#idioms
❌ A fast shower 🚿
✅ A quick shower
❌ Respond the door 🚪
✅ Answer the door
❌ Strong rain 🌧
✅ Heavy rain
❌ Celebrate a party 🎉
✅ Throw a party
❌ Ask for a wish 🤞🏻
✅ Make a wish
❌ Strong taste 😑
✅ Big taste
❌ Lost the time ⏳
✅ Waste time
❌ Nice dreams 🛌
✅ Sweet dreams
#sirjimmy
#teamjimmy
#idioms
🤨English Idioms Describing Character And Personality😜
✅1. Pain in the neck – an irritating, annoying person
Ex. Sarah is such a pain in the neck these days.
✅2. A people person – an outgoing person who gets along with people really well and is a good listener
Ex. Tom is enthusiastic and positive and he is a people person.
✅3. Party animal – someone who likes to attend parties often
Ex. Are you going out again tonight? You are such a party animal.
✅4. Cheapskate – a mean person who doesn’t like spending money
Ex. He was always a cheapskate even though he was earning $200,000 a year.
✅5. Happy camper – a person who is always happy and satisfied. We often use ‘happy camper’ in the negative.
Ex. The apartment was much smaller than I expected, I was not a happy camper.
✅6. Nerd – someone who is very interested in science or technology, particularly in computers
Ex. He spends all weekends at his laptop, he is such a nerd.
✅7. Life and soul of the party – someone who is energetic, and good fun during social occasions.
Ex. It was a great night, Jim was life and soul of the party.
✅8. Dipstick – a person who seems to be stupid (very informal)
Ex. I don’t know whether to laugh or be angry at his behaviour. What a complete dipstick!
✅9. Down-to-earth – someone who is practical and close to reality, who accepts other people as equals
Ex. Despite his wealth, he was a down-to-earth man. He was very generous and had a kind heart.
✅10. Early bird – a person who wakes up, arrives to work, etc. before the usual time
This expression comes from the English proverb “The early bird catches the worm”.
Ex. My Mum is the early bird in our family, she gets up at 5 o’clock in the morning.
✅11. Larger than life – someone who is more exciting or interesting than other people
Ex. All who knew him would agree that his personality was larger than life, he was a joy to be around.
#Idioms
#Teamjimmy
#sirjimmy