Что делать если нужно поставить какую-то 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
I present a soft, relaxed, cozy, warm soul (and body 😉) plaid shirt.
Autumn is coming 🍂 and we will all need it paired with denim, leather jackets and trench coats soon. And for those who can't wait - try to style with summer cotton skirts, one love 💕
#inspirationINVOGA
🌺 Flowers always, 🌼 flowers everywhere!
🌺Flower Like:
- choker
- belt (I liked it very much 👌🏼 - as an alternative to a choker)
- brooch
🌸Flower on:
- shoes
- swimsuit
- shirt
#inspirationINVOGA
TOP 5 ideal neighbors for metallic trousers:
1. White T-shirt
2. Black/white tank top
3. Basic jersey
4. Masculine shirt or jacket
5. Classic longsleeve
Shine with pleasure and let the whole world be reflected in your pants - no matter how it sounds😂
#inspirationINVOGA
There are five must-have accessories for the upcoming (and for someone have already come) cold weather:
1. Voluminous long scarf
2. Bib
3. Short or long gloves
4. Puffy/quilted bag
5. Balaclava
#inspirationINVOGA
Let's look at the beauty celebration from Prada about the new fragrance PARADOXE
Here we have everything in style:
conciseness in color and silhouettes;
oversized jackets
socks
a drop (or not a drop) of glitter and a few feathers
leather
crossbody with very short straps
And triangles, triangles, triangles😊
#inspirationINVOGA
Hoodie + Coat - Yes or No?
As for me, there is nothing better and more convenient than such a couple for daily routine worries that have to be done more often than bright events happen😉🤷🏼♀️
While it is still not too cold, the coat can be left open. The hoodie can be worn without an underlayer. However, it is also not forbidden to pry off the turtleneck to save the throat and tighten the belt on the coat.
#inspirationINVOGA
A bit of street style from Paris Fashion Week Spring 2023:
- total denim, asymmetric denim, double waist,
- loose knit jersey,
- bomber jackets, leather coats, and trench coats,
- fit and transparency,
- balaclavas,
- over-the-knee boots and high boots
#inspirationINVOGA
☕️It's cloudy and rainy outside the window☔️. The mood is to wrap yourself in a knitted dress and enjoy your favorite cappuccio - what could be better for a Wednesday morning?
Favorite🏆 styles:
1. Knitted dress with sneakers
2. Knitted dress with trumpet/jockey boots that overlap with the dress.
3. Knitted dress overskirt
4. Knitted dress with rough, worn leather
#inspirationINVOGA
I went to Etro Spring 2023 street style for paints, prints, and textures, sharing the mood I caught there and photos made by my own hands 🤲🏼
I’ll start with the atmosphere, the show, and as a result, the street style took place in the industrial zone of Milan and was accompanied by a roar, howl, and signals of disgruntled trucks 🚚🚛 , traffic that was not blocked, but photographers and street stylers scurrying everywhere and everywhere, significantly complicated it 🔴
And then everything is as expected - notes of ethnicity in the form of jersey with fringes, small and complex prints, bright saturated colors, patchwork, some leather, but more suede.
I have loved Etro for many years and have chosen the perfect accents for my wardrobe there! ❤️🤎
#inspirationINVOGA
In the meantime, Milan is taking over the baton of Fashion week, in which I am also going to participate and share with you. We review and study London street style.
Lots of ruffles and frills, puffed sleeves and huge collars, brocade and tulle combined with a bit of English stiffness, plaid, lots of Mary Jane variations, golfs, leather, and punk casualness 🎸🤘🏼
#inspirationINVOGA
Who has butterflies in their stomach? 🦋😉 Release! This summer, and next fall, you can definitely👌🏼
We are not limited to flowers, we add butterflies in all dimensions - tops, jewelry, bags, belts, shoes, and when autumn comes, it will come to jackets.
Catch it while the season and treat with care😉
#inspirationINVOGA