Что делать если нужно поставить какую-то 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
🎙President Vladimir Putin's statement at the state awards ceremony for Russian athletes(Moscow, April 22, 2026)
💬 I am sincerely pleased to congratulate everyone on your successes. Your performances and results are a substantial contribution to reaffirming Russia’s leading position in world sport – a strong and unshakable position, despite all the underhanded attempts to weaken it.
☝️The disgraceful – and, I would say, cowardly – politically motivated conduct of the previous leadership of the International Olympic Committee inflicted enormous damage on the Olympic movement and on the very principles of Olympism.
Selective sanctions against Russian athletes, imposed under the pretext of condemning Russia’s actions to defend our people and our interests in the context of the conflict in Ukraine, while ignoring numerous other similar tragedies and armed conflicts around the world, merely exposed the corruption and political bias of a significant part of the international sporting establishment.
👉I hope that the new leadership of the International Olympic Committee and other international sports organisations will overcome this legacy as soon as possible – a heavy and shameful legacy left by their predecessors.
I am certain that many more sporting triumphs lie ahead for you, as well as for your teammates representing a wide range of disciplines – including at the biggest international competitions – and, without fail, under our national flag and to the sound of Russia’s national anthem.
Russia is steadily returning to the world’s sporting arenas, and doing so with dignity. Last season, our swimmers, fencers, canoeists, gymnasts, judokas and wrestlers all delivered brilliant victories.
The truly special – indeed unique, without any exaggeration – achievement was the triumph of Russia’s Paralympians in Milan. As you know, they secured third place in the overall standings with a team that was several times smaller than those of their main rivals. This was an outstanding result. These victories were won not by numbers, but by skill, talent and the will to win.
Russia will continue to develop sport in all areas, ensuring the broadest possible opportunities for participation in elite sport, professional sport and mass sport alike, while actively promoting sport above all among children and young people. Because, as we all know well, sport is not simply about physical strength and agility – it is a way of life built on the values of health, mutual respect, and, crucially, determination and responsibility.
Read in full
#TeamRussia
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russian Paralympic Committee:
#TeamRussia finishes THIRD in the medal standings at the 2026 Paralympic Games!
Despite a team of just six athletes and one guide, our Paralympians delivered a phenomenal performance.
12 MEDALS:
🥇 8 gold
🥈 1 silver
🥉 3 bronze
In the overall standings, Russia finished 3rd, behind only China and the US with many more athletes on the teams.
💬 President of the Russian Paralympic Committee Pavel Rozhkovnoted:
The results have surpassed all expectations! Even with a small team, Russia made a powerful statement and marked a triumphant return to the international sports arena.
👏 Congratulations and massive respect go to our outstanding athletes: Anastasia Bagiyan and her guide Sergey Sinyakin, Varvara Voronchikhina, Ivan Golubkov, Alexei Bugaev, Dmitrii Fadeyev and Monzer Philippe Shebbo.
🇷🇺Russisches Paralympisches Komitee:
#TeamRussia belegt den DRITTEN PLATZ im Medaillenspiegel bei den Paralympischen Spielen 2026!
Trotz eines Teams von nur sechs Athleten und einem Guide lieferten unsere Paralympioniken eine phänomenale Leistung ab.
12 MEDAILLEN:
🥇 8 Gold
🥈 1 Silber
🥉 3 Bronze
Im Gesamtklassement belegte Russland Platz 3 – hinter China und den USA, die beide mit deutlich größeren Teams angetreten sind.
💬 Der Präsident des Russischen Paralympischen Komitees, Pavel Rozhkov, erklärte:
Die Ergebnisse haben alle Erwartungen übertroffen! Auch mit einem kleinen Team hat Russland ein starkes Zeichen gesetzt und eine triumphale Rückkehr auf die internationale Sportbühne gefeiert.
👏 Herzlichen Glückwunsch und größten Respekt an unsere herausragenden Athleten: Anastasia Bagijan und ihren Begleiter Sergej Sinyakin, Warwara Worontschichina, Iwan Golubkow, Alexej Bugajew, Dmitrii Fadejew und Monzer Philippe Shebbo.
@RusBotschaft
#Russland#Sport
Прорыв 2021 года 🐻🔥
Даниил Медведев, вторая ракетка мира, показал феноменальный результат в уходящем 2021 году⚡Даниил завоевал свои чемпионские титулы на турнирах:
🔹Open 13 Provence в Марселе (8-14 марта)
🔹Mallorca Championships на Майорке (20-26 июня)
🔹National Bank Open Presented by Rogers в Торонто (9-15 августа )
🔹US OPEN ITF Grand Slam в Нью-Йорке (30 августа-12 сентября)
Даниил также завоевал несколько командных титулов, о которых мы расскажем уже в следующих постах🤫
Поздравляем с незабываемым сезоном и желаем самых ярких побед и достижений в 2022 году🏆🔥
#формулатх#теннис#tennis#formulatx#atp#teamrussia
Аслан Карацев остается в ТОП-20 мирового рейтинга после окончания сезона💪😄
Аслан показал отличный результат в 2021 году, завоевав титулы на турнирах:
- ATP Qatar ExxonMobil Open (8-14 марта)
- ATP Kremlin Cup (16-24 октября)
- ATP Dubai Duty Free Tennis (2-6 ноября)
Аслан провёл великолепный сезон🤩
Желаем в 2022 году получить еще больше титулов и одержать еще больше побед🏆
#tennis#formulatx#формулатх#теннис#atp#wta#teamrussia
🇷🇺🤘🏼Андрей Рублёв стал победителем турнира ATP-250 в Марселе в одиночном и парном разряде 💪🏻
👏🏻Первый титул в начале сезона🔝 Поздравляем и желаем продолжать завоевывать титулы❗
#formulatx#andreyrublev#формулатх#андрейрублёв#teamrussia
🚨В завершении рубрики “Итоги года для российского тенниса 2021”, вспоминаем о замечательных результатах наших спортсменов на Олимпийских играх в Токио‼️
🔹Карен Хачанов серебро финал одиночного разряда
🔹Анастасия Павлюченкова и Андрей Рублёв взяли золото в финале парного разряда
🔹Елена Веснина и Аслан Карацев взяли серебро в финале парного разряда
🙏Благодарим всех спортсменов с невероятно насыщенным победами год! Мы верим в вас и гордимся вами❤️ Это было очень мощно👍
#tennis#formulatx#формулатх#теннис#throwbackthursday#atp#wta#teamrussia