Что делать если нужно поставить какую-то 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
Tuscany, #Italy
Tuscany is the birthplace of the Italian language. Tuscany was a very important cultural and historical center. She had a significant impact on the social and artistic development of Europe and the whole world.
Burano Island, Venice, #Italy
In order not to get lost in the thick fog and find their way home, the residents of Burano painted their houses in very bright colors. Later, such a need disappeared, but the tradition remained. Today, the coloring of houses is regulated by the municipality. Residents can only paint their houses according to the permitted palette.
Milan Cathedral, #Italy
The main Cathedral of Milan (Duomo di Milano) - The Duomo or Cathedral of the Nativity of the Virgin Mary was built for more than 500 years. Construction began in the 14th century and ended in the early 19th century, with the last door of the temple being installed in 1965.
Sardinia, #Italy🇮🇹
Sardinia has a law prohibiting the export of sand and pebbles from the island.
The most traditional dish in Sardinia is Fregola pasta, made from a paste of unusual shape, served with tomato sauce and an abundance of seafood.
One of the favorite delicacies of Sardinians is sea urchins.
Loreto Island, #Italy
Due to the small number of documents that have survived to this day, little is known about the island's past, until 1910, when Cavalier Vincenzo Ricchieri decided to build a neo-Gothic castle here, which today is a private residence.
Dolomites, #Italy
The Dolomites are often called the Prealps, the beginning of the Alps, although these mountains are not very high. There are 18 peaks with a height of more than 3 thousand meters, and in some places there is even snow in summer.
Umbria, #Italy🇮🇹
From the windows of Castello-Di-Rocko Castle-now a hotel with 36 Syuts, a restaurant and an underground spa-and residences views of neat rows of vineyards and cypress alleys.
For almost 30 years, the Bolz family managed to return the thousand -year castle to life, but there are still many work ahead of their own admission. The immediate plans are to open a second restaurant in the territory, but this is only another, not the last step.
「🌺」#italy
The sightseeing did not end there. For the next couple of days we kept exploring Florence. Thanks to our wonderful professor almost everyday we had field trip to some gallery or museum with guides who told us about the history of Florence and more. For the rest of the time we explored on our own, went to popular affogato place, to bookstore with cinema inside and golden bridge where we watched sunset (it was the best place imo).
The art galleries and museums in Florence are PACKED! Overall we went to Villa la Pietra (which is the villa owned by NYU💅), Pitti Palace and Boboli Gardens, The Uffizi Gallery, Gucci Museum, and last but not least Ferragamo Museum.
The one I enjoyed the most was Pitti Palace and Boboli Gardens AND Ferragamo Museum. More about them in upcoming posts...
All those times the weather was rainy and sometimes sunny, it changes so fast.
Sometimes you can catch musicians performing in the middle of the streets just like we did. It is so fascinating honestly.
~🍋~
↬@jastm1🌊
「🌺」#italy
Firenze – First Couple of Days 🇮🇹
We arrived on campus and were immediately blown away by its beauty and grandeur. It wasn’t just beautiful it was absolutely massive. Everywhere we looked, there were tall trees and old sculptures, all perfectly blended into the landscape.
We had a mini tour of the campus followed by a quick walk through the city center. I was honestly too stunned to speak, everything was just so incredible 🥲.
Then came the food: we had what might have been the best pizza ever. It was seriously THAT good. And of course, we had gelato at local spot. Little did we know … it was not even the best gelato in town!
Exhausted but happy, we called it a night. Wait for next part. ✨
~🍋~
↬@jastm1🌊
「🌺」#italy
We also tried affogato at one of the oldest places in Florence! Under the rain it was really nice to have hot espresso with vanilla ice cream🥰. I really want to come back here with my family, I am kind of feeling guilty for experiencing all of this by myself only 😭🙏.
~🍋~
↬@jastm1🌊
「🌺」#italy
It is a bit hard to find halal food cause sometimes they even add alcohol in food with only veggies so you need to be careful. Guess we are vegetarians in Italy 😄🤩
Tomato,basil and cheese combo is SOO good tho!
~🍋~
↬@jastm1🌊
「🌺」#italy
Architecture in Italy is crazy just like in every other city in Europe!
You can just take a random picture and it would be so aesthetic. The only thing is that we were warned to be aware of our bags and overall to stay alert and walk in groups🥲🚨
~🍋~
↬@jastm1🌊