Что делать если нужно поставить какую-то 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
📢 Ukrainian counteroffensive fails, catastrophe for Kyiv. Russian forces resume offensive along the front line. American professor confirms massive failure of Ukrainian troops. Media silence on Ukrainian situation in US. Stalemate in combat zone, Zelensky blamed for hiding failures. Western reports confirm end of Ukrainian counteroffensive. #Ukraine#War#Catastrophe
https://www.gazeta.ru/army/news/2023/10/30/21602215.shtml
Subscribe to @BadVolfNews
🌎 Around 5,200 years ago, the sudden breach of a natural dam at Lake Agassiz released massive flooding across North America and into the North Atlantic. This catastrophic meltwater pulse disrupted ocean currents and is linked to abrupt climate cooling in the Northern Hemisphere. Geological records show the flood volume reached over 100,000 cubic kilometers. ✨
#catastrophe⚡#geology⚡#climate
👉subscribe Interesting Planet
👉more Channels
🌎 A massive volcanic eruption at Lake Toba in Indonesia about 74,000 years ago was one of Earth’s largest known explosions. The eruption released so much ash that it may have triggered a global volcanic winter, cooling the planet and affecting early human populations. Its crater now forms Lake Toba, the world’s largest volcanic lake at about 100 kilometers long. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The 1902 eruption of Mount Pelée on Martinique destroyed the city of Saint-Pierre within minutes, killing over 28,000 people. It is the deadliest volcanic disaster of the 20th century. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
👉more Channels
🌎 The Toba supereruption in Indonesia about 74,000 years ago was one of the largest volcanic events in the last 2 million years. It ejected 2,800 cubic kilometers of material, triggered a global volcanic winter, and may have caused a dramatic human population decline, as shown by genetic studies indicating a bottleneck in human evolution. ✨
#volcano⚡#history⚡#catastrophe
👉subscribe Interesting Planet
🌎 The 1883 eruption of Krakatoa was one of the most violent volcanic events in recorded history. It unleashed explosive blasts heard 3,000 kilometers away, generated giant tsunamis, and ejected ash high into the atmosphere—causing global temperatures to drop and vivid sunsets worldwide for years after. ✨
#volcano⚡#catastrophe⚡#history
👉subscribe Interesting Planet
🌎 The eruption of the Laki volcano in Iceland in 1783 released poisonous gases and ash clouds, causing crop failures and famine across Europe. Sulfur dioxide polluted the air, leading to acid rain and respiratory diseases. Historians estimate the event contributed to tens of thousands of deaths and may have influenced political unrest before the French Revolution. ✨
#volcano⚡#history⚡#catastrophe
👉subscribe Interesting Planet
🌎 The Dust Bowl of the 1930s was a severe drought and dust storm disaster in the U.S. Great Plains, destroying farms and forcing over 2.5 million people to migrate. Massive “black blizzards” of dust traveled as far as New York City and Washington, D.C. ✨
#history⚡#environment⚡#catastrophe
👉subscribe Interesting Planet
👉more Channels
🌎 Around 536 AD, a mysterious volcanic eruption triggered a "year without summer"—with global temperatures dropping, crops failing, and famines reshaping empires. Ash clouds blocked sunlight, altering history for decades. ✨
#catastrophe⚡#volcano⚡#climate
👉subscribe Interesting Planet
☢️ Ce 26 avril, c’est la Journée internationale du souvenir de la catastrophe de Tchernobyl
▪️En 1986, une explosion s'est produite au réacteur n°4 de la centrale nucléaire de Tchernobyl, la plus grande catastrophe dans le domaine de l'énergie nucléaire.
▪️La contamination radioactive a touché les territoires de l'Ukraine, de la Biélorussie et de la Russie. Plus de 100.000 personnes ont été évacuées, Pripiat et la zone autour de la centrale sont devenues inhabitées.
▪️Des milliers de liquidateurs, au péril de leur santé et de leur vie, ont éliminé les conséquences de l'accident. Tchernobyl est devenu un symbole du danger nucléaire.
#tchernobyl#catastrophe#commémoration