Что делать если нужно поставить какую-то 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
#Sweden, national parliament election:
S (S&D) is largest in all constituencies but two in Scania where SD (ECR) leads.
SD, M (EPP), KD (EPP), L (RE) are together stronger in the South.
S, C (RE), V (LEFT), MP (G/EFA) together do best in the North and the three largest cities.
➤ europeelects.eu/sweden
🇸🇪#Sweden: The Swedish Coast Guard has seized a Syrian-flagged vessel named Jin Hui, suspected of being part of Russia’s so-called "shadow fleet".
The ship was sailing in Swedish territorial waters south of Trelleborg and had appeared on multiple sanctions lists. Its destination was unclear. Authorities also suspect the vessel may have been operating under a false flag and was reportedly carrying no cargo.
(via Reuters)
#Sweden🇸🇪
The Luleo Archipelago is a group of Swedish islands in the northern part of the Bayer Belonian, located near the city of Luleo and the mouth of the Lule River.
The sea freezes in January and remains frozen until March - April. Ice roads are cleaned by the four populated islands.
📍Sweden🇸🇪
Gorgeous evening view from the Liseberg amusement park in Sweden. 🎢
Liseberg Amusement Park is also a true symbol of love, as it was built in 1923 by merchant Lamberth for his terminally ill wife Lisa. He transformed the former pastureland into a real garden with trees, flowers, and water areas. 🌳🌺😍
After Lisa's death, the park was donated by her husband to the state, and currently, it attracts about 3 million visitors per year, making it one of the most popular entertainment and leisure destinations in Europe.
#Sweden
@voyage
🇸🇪#Sweden - 🇷🇺#Russia: The Swedish Coast Guard, together with the police, has boarded another vessel suspected of operating under a false flag off the coast of Trelleborg.
The oil tanker, named "Sea Owl I", is believed to be part of Russia's shadow fleet. It was reportedly sailing under an alleged false flag on its way to the port of Primorsk in Russia after departing from Santos, Brazil. Investigators were also alerted by the fact that the ship appeared unusually light and insufficiently loaded.
After the Coast Guard boarded and took control of the vessel, the captain, which is a Russian citizen, was taken in for questioning, however, he has not been arrested yet. Meanwhile, the Russian embassy in Sweden stated earlier today that it is "monitoring the situation", with Russian officials describing the boarding as an act of "piracy".
(via Göteborgs-Posten & Reuters)
🇸🇪#Sweden - 🇷🇺#Russia: Swedish special forces, along with aviation police and the coast guard, have seized a sanctioned Russian vessel which was sailing under a false flag.
The operation took place this Friday while the ship was sailing in Swedish territorial waters in the Baltic Sea near Trelleborg.
The ship was involved in the theft of grain from the territories that Russia has occupied since July 2025.
During last summer, the ship is said to have had its flag changed from a Russian flag to a Guinean flag.
(via Göteborgs-Posten)
🇸🇪#Sweden - 🇷🇺#Russia: The Swedish Coast Guard has boarded the Russian vessel ADLER in the Baltic Sea and carried out inspections on the ship which was reported to regularly transport military cargo to Russian allies in Africa.
The ADLER is operated by M Leasing LLC, a logistics company under EU sanctions and linked to the Russian Ministry of Defence.
The ship was forced to anchor off the Swedish coast yesterday morning after reportedly suffering an engine failure.
According to Swedish media, the crew is cooperating with the Swedish Coast Guard during the inspection.
(via Reuters; 📹 via @wartranslated on X)