Что делать если нужно поставить какую-то 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
Circle dances can be seen in the tradition of dancing round the may pole.
Circle dance, or chain dance, is a style of dance done in a circle or semicircle to musical accompaniment, such as rhythm instruments and singing. Circle dancing is probably the oldest known dance formation and was part of community life from when people first started to dance.
Dancing in a circle is an ancient tradition common to many cultures for marking special occasions, rituals, strengthening community and encouraging togetherness.
The circle dance of Germany was called "Reigen", which dates from the 10th century. Dancing around the church or a fire was frequently denounced by church authorities which only underscores how popular it was.
Circle dances were also found in Czech Republic, dating to the 15th century. Dancing was primarily done around trees on the village green.
a reference comes from Bulgaria, in a manuscript of a 14th-century sermon, which calls chain dances "devilish and damned."
#tradition
@EuropeanTribalism
On traditions
The oldest traditional clothing in the Alpine region is the so called 'Bregenzerwälder Juppe'. It is worn by women of the region of Vorarlberg, a county of Austria. It goes back to the 15th century and has not changed ever since.
Unmarried girls wear a 'Schappale', an artful head garment, handmade by only a couple of artisans.
The headwear and dress often are worn lifelong on special occasions and then given to the next generation.
#tradition#custom
@EuropeanTribalism
Ein Bett auf dem Ofen? In Russland war das lange Realität!
Sofja erklärt, warum Russen auf Öfen schliefen 🇷🇺🇷🇺
#welcometoRussia#Russland#tradition#RusslandEntdecken
🪆Fenster nach Russland
🌎 In Indonesia’s Tana Toraja region, families celebrate Ma’nene, a ritual where they exhume deceased relatives, clean their bodies, and dress them in fresh clothes. This custom honors ancestors and reinforces family ties. Some mummies are carried through the village during the ceremony, which happens every few years. ✨
#tradition⚡#anthropology⚡#festival
👉subscribe Interesting Planet
👉more Channels
🌎 In Papua New Guinea, the Kaningara people of the Sepik River region perform a crocodile-scarification ritual. Teenage boys undergo elaborate skin-cutting ceremonies that create raised scars resembling crocodile scales, symbolizing a spiritual connection with the river’s sacred crocodiles. The process involves hundreds of cuts and can last several hours. ✨
#ritual⚡#anthropology⚡#tradition
👉subscribe Interesting Planet
👉more Channels
🌎 In Thailand, the annual Phi Ta Khon festival in Dan Sai features villagers wearing ghost masks made from rice husks and coconut leaves. This tradition is linked to Buddhist legends and includes parades, music, and playful pranks. The festival can attract over 50,000 people each year. ✨
#culture⚡#tradition⚡#festival
👉subscribe Interesting Planet
👉more Channels
🌎 In Venezuela, the moriche palm thrives in flooded tropical savannas and yields “buriti” fruit, rich in vitamin A. Locals use its golden, sweet pulp for juices, jams, and even sun-protective oil, making this tree a true “tree of life” for Amazonian communities. ✨
#botany⚡#nutrition⚡#tradition
👉subscribe Interesting Planet
🌎 Each spring, the Tinku festival in Bolivia brings rival villages together for ritual fistfights. This tradition, rooted in pre-Columbian beliefs, is seen as an offering to Pachamama, or Mother Earth, to ensure a good harvest. Participants don colorful clothes and fight under strict rules; local police and medics oversee the event. ✨
#culture⚡#tradition⚡#Bolivia
👉subscribe Interesting Planet
👉more Channels
🌎 In Scotland’s remote Orkney Islands, residents celebrate “New Year’s Ba’,” a centuries-old street football match. Townspeople split into two teams and battle for hours to carry a hand-made leather ball to opposing goals. The tradition dates back at least to the 17th century and draws hundreds of participants and spectators each year. ✨
#tradition⚡#Scotland⚡#Orkney
👉subscribe Interesting Planet
👉more Channels
The Ancient Romans put toast in their wine because they believed it was good for health. This is where the tradition of "raising a toast" comes from. 🍷🍞
[Read more]
@googlefactss🍷🍞#AncientRome#Toast#Wine#History#Tradition
Dordolec are hanging dolls or stuffed toys in Albania, mostly in the south. They hang outside homes to protect against the evil eye, which means bad luck from jealous looks. These dolls are believed to catch negative energy and stop harm to people and property. The custom grew again after the 1990s when social differences increased.
[Read more]
@googlefactss
#Albania#Dordolec#EvilEye#Tradition🧸🛡️