Что делать если нужно поставить какую-то 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
🚀 On April 12, 1961, at 09:07 Moscow time, the Vostok spacecraft with pilot-cosmonaut Yuri Gagarin on board blasted off from the Baikonur Cosmodrome, marking the beginning of the space age in the history of mankind.
Yuri Gagarin spent 108 minutes in space, making a complete orbit around the Earth, and successfully landed.
While in orbit, he maintained radio contact with Earth, made observations through a porthole, controlled the operation of the ship's systems, and carried out simple experiments.
📰 Even his wife did not know about this feat. The news about Yuri's flight came out only 55 minutes after the launch of the Vostok rocket, becoming the most quoted report in the world.
Two days later, many thousands of people with flowers and welcome posters took to the streets of Moscow, honouring the cosmonaut who had arrived in the capital. At the end of April, our compatriot went on a foreign tour, travelling through more than 30 countries in two years, where he was welcomed as a hero.
#CosmonauticsDay
О мероприятии по случаю Международного дня полета человека в космос
12 апреля 2024 года по случаю Дня космонавтики Временный поверенный в делах Российской Федерации в Румынии Е.С.Копнина возложила цветы к бюсту Ю.А.Гагарина, советского летчика-космонавта, первого человека в мировой истории, совершившего полёт в космическое пространство. В торжественном мероприятии в Бухаресте приняли участие представители дипломатического корпуса, аккредитованного в Румынии, бизнеса, соотечественники, румынские общественные организации и СМИ.
Российский дипломат поздравила гостей с праздником, отмечаемым ежегодно в день первого полета человека в космос, знаменовавшего важнейший шаг в истории человечества, впервые покинувшего колыбель родной планеты. Она отметила объединяющую силу Международного дня космонавтики, когда представители множества стран отдают дань памяти и восхищения мужеством, талантом и самоотверженным трудом всех поколений ученых, конструкторов, летчиков, внесших вклад в изучение и мирное освоение космического пространства.
Мероприятие открыло серию культурных акций Посольства, посвященных Дню космонавтики. В их числе – конкурс и выставка детского рисунка «Я рисую космос» и показ на румынском языке познавательного документального фильма «Космическая история России», предоставленного Ассоциацией планетариев России. Кроме того, вниманию всех, увлеченных космической тематикой, будут представлены в переводе на румынский язык драматическая кинолента «Вызов», первый художественный фильм, снятый в условиях невесомости на Международной космической станции, и исторический фильм «Время первых» о первом выходе человека в открытый космос, совершенном советским космонавтом А.А.Леоновым 18 марта 1965 года.
ПРЕСС-СЛУЖБА ПОСОЛЬСТВА
#CosmonauticsDay#ДеньКосмонавтики
“Having orbited Earth in a spaceship, I saw for the first time how beautiful our planet is.
People, let us preserve and increase this beauty and not destroy it!”
— Yuri Alekseyevich Gagarin
🚀 The world changed forever in those moments when Vostok-1 launched from the Baikonur Cosmodrome, and Yuri #Gagarin became the first person in history to enter Earth’s orbit and circle our planet. This collective feat of the entire Soviet Union, its scientists, and cosmonauts marked the beginning of the space era in human history.
🌏 Before the launch of the spacecraft, Yuri Gagarin addressed the people of the entire planet with these inspiring words:
“Dear friends, both familiar and unknown, compatriots, people of all countries and continents!
In just a few minutes, a mighty spacecraft will carry me into the vast expanses of the universe. What can I say to you in these final moments before the launch?
My entire life now seems to me like one beautiful moment. Everything I have lived through and accomplished was done for the sake of this moment.
Am I happy to be embarking on this spaceflight? Of course, I am! After all, throughout history, it has been the highest happiness for people to participate in new discoveries.
Now, only a few minutes remain until the launch. I want to say goodbye to you, my dear friends, as people always say to each other when setting off on a long journey. How I wish I could embrace you all — both those I know and those I don’t, those far away and those close by!
Until we meet again!”
#CosmonauticsDay#Gagarin#FirstInSpace
“Having orbited Earth in a spaceship, I saw for the first time how beautiful our planet is.
People, let us preserve and increase this beauty and not destroy it!”
— Yuri Alekseyevich Gagarin
🚀 The world changed forever in those moments when Vostok-1 launched from the Baikonur Cosmodrome, and Yuri #Gagarin became the first person in history to enter Earth’s orbit and circle our planet. This collective feat of the entire Soviet Union, its scientists, and cosmonauts marked the beginning of the space era in human history.
🌏 Before the launch of the spacecraft, Yuri Gagarin addressed the people of the entire planet with these inspiring words:
“Dear friends, both familiar and unknown, compatriots, people of all countries and continents!
In just a few minutes, a mighty spacecraft will carry me into the vast expanses of the universe. What can I say to you in these final moments before the launch?
My entire life now seems to me like one beautiful moment. Everything I have lived through and accomplished was done for the sake of this moment.
Am I happy to be embarking on this spaceflight? Of course, I am! After all, throughout history, it has been the highest happiness for people to participate in new discoveries.
Now, only a few minutes remain until the launch. I want to say goodbye to you, my dear friends, as people always say to each other when setting off on a long journey. How I wish I could embrace you all — both those I know and those I don’t, those far away and those close by!
Until we meet again!”
#CosmonauticsDay#Gagarin#FirstInSpace
“Having orbited Earth in a spaceship, I saw for the first time how beautiful our planet is.
People, let us preserve and increase this beauty and not destroy it!”
— Yuri Alekseyevich Gagarin
🚀 The world changed forever in those moments when Vostok-1 launched from the Baikonur Cosmodrome, and Yuri #Gagarin became the first person in history to enter Earth’s orbit and circle our planet. This collective feat of the entire Soviet Union, its scientists, and cosmonauts marked the beginning of the space era in human history.
🌏 Before the launch of the spacecraft, Yuri Gagarin addressed the people of the entire planet with these inspiring words:
“Dear friends, both familiar and unknown, compatriots, people of all countries and continents!
In just a few minutes, a mighty spacecraft will carry me into the vast expanses of the universe. What can I say to you in these final moments before the launch?
My entire life now seems to me like one beautiful moment. Everything I have lived through and accomplished was done for the sake of this moment.
Am I happy to be embarking on this spaceflight? Of course, I am! After all, throughout history, it has been the highest happiness for people to participate in new discoveries.
Now, only a few minutes remain until the launch. I want to say goodbye to you, my dear friends, as people always say to each other when setting off on a long journey. How I wish I could embrace you all — both those I know and those I don’t, those far away and those close by!
Until we meet again!”
#CosmonauticsDay#Gagarin#FirstInSpace
📅April Programme at the Russian House Brussels
We are pleased to present our April programme — a rich and diverse series of cultural, educational and artistic events.
✨ This month:
— 🎨 Family space art workshop for children
— 🎬 Space Documentary Film Days dedicated to Cosmonautics Day
— 🎼 Concerts and musical evenings, including a special programme of the Bolshoi Theatre
— 📚 Lectures and historical meetings
— 🇷🇺 Russian language workshops and conversation club
— 🎭 Theatre performance and film screenings for all ages
🖼 Throughout April, discover our exhibitions:
— “The Amazing Earth”
— “Energy of Space” by Sergey Kraynev
— “Captain Cousteau in Russia”
— “When Art Nouveau meets Artificial Intelligence”
📍 All events take place at the Russian House Brussels or online
🔗 Full programme and registration: rushouse.be
We look forward to welcoming you!
#RussianHouseBrussels#BrusselsEvents#Culture#RussianCulture#Art#Music#Cinema#Education#CosmonauticsDay#Brussels