Что делать если нужно поставить какую-то 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
🇷🇺🇮🇳📞 Russia's President Vladimir Putin and Prime Minister of the Republic of India Narendra Modispoke over the phone.
The President of Russia warmheartedly congratulated Narendra Modi on the success of the Indian People's Party in the general parliamentary elections that finished a few days ago. This reflects the support of the political course pursued by the Indian leadership, recognition of the results achieved in the country's socioeconomic development, and its strengthening international authority.
Sides expressed their satisfaction with the current level of especially privileged strategic partnership between Russia and India, which will continue to expand in all areas.
It was agreed to continue constructive personal interaction between the two countries' leaders.
📃 A message of congratulations was also sent to Narendra Modi:
"The results of the voting once again reaffirm your high personal political reputation, as well as the support of the course you pursue towards India’s fast socioeconomic development and protection of its interests on the global stage.
We consider relations of especially privileged strategic partnership with New Delhi of great importance. I am confident that further promotion of mutually beneficial cooperation and giving it new substance aligns with the interests of the Russian and Indian nations.
Of course, I also hope that we will continue our open dialogue and constructive joint work on the topical issues on bilateral and international agenda."
#RussiaIndia
🇷🇺🚀
🇮🇳 On April 3, the Russian House in New Delhi hosted a photo exhibition from the TASS News Agency’s archive to mark the 40th anniversary of spaceflight of the first Indian cosmonaut Rakesh Sharma as part of the Soviet crew.
The event was attended by representatives of the expert community and diplomatic corps, media, employees of the Indian Space Research Organization, students and compatriots.
💬 The exhibition was inaugurated by Roman Babushkin, Minister Counsellor & DCM, Russian Embassy in India, Evgeny Pakhomov, Chief of the Indian Bureau, TASS News Agency, and Sanjeev Kumar Varshney, Adviser & Head, International Cooperation (Bilateral) Division, Department of Science & Technology, Ministry of Science & Technology, Government of India.
The audience was also addressed by Wing Commander Rakesh Sharma himself through a video message. He shared his impressions of preparations for the flight, noted the significance of this event as well as expressed confidence in the further successful development of bilateral cooperation in the space sector.
🎬 A documentary titled “How I Became a Cosmonaut” was also shown as part of the event.
📸 The exposition that contains 40 unique archival photographic materials will last until April 16, 2024.
🔸@RusEmbIndia
#RussiaIndia
🇷🇺
🇮🇳 On June 24, in Tehran, on the sidelines of the 19th Asia Cooperation Dialogue Ministerial Meeting, Russian Deputy Foreign Minister Andrey Rudenko had a meeting with Dammu Ravi, Secretary (ER), Ministry of External Affairs, Government of India.
💬 The parties exchanged views on topical issues of the Russian-Indian cooperation, including in the economic and transport spheres. Particular attention was paid to the interaction within BRICS and the SCO.
🤝 They reaffirmed the commitment to further intensify bilateral political dialogue.
🔸@RusEmbIndia
#RussiaIndia
🇷🇺🇮🇳📞 Russia's President Vladimir Putin and Prime Minister of the Republic of India Narendra Modispoke over the phone.
The President of Russia warmheartedly congratulated Narendra Modi on the success of the Indian People's Party in the general parliamentary elections that finished a few days ago. This reflects the support of the political course pursued by the Indian leadership, recognition of the results achieved in the country's socioeconomic development, and its strengthening international authority.
Sides expressed their satisfaction with the current level of especially privileged strategic partnership between Russia and India, which will continue to expand in all areas.
It was agreed to continue constructive personal interaction between the two countries' leaders.
📃 A message of congratulations was also sent to Narendra Modi:
"The results of the voting once again reaffirm your high personal political reputation, as well as the support of the course you pursue towards India’s fast socioeconomic development and protection of its interests on the global stage.
We consider relations of especially privileged strategic partnership with New Delhi of great importance. I am confident that further promotion of mutually beneficial cooperation and giving it new substance aligns with the interests of the Russian and Indian nations.
Of course, I also hope that we will continue our open dialogue and constructive joint work on the topical issues on bilateral and international agenda."
#RussiaIndia
🇷🇺🇮🇳 Russia’s Foreign Minister Sergey Lavrov and Minister of External Affairs of India Dr. Subrahmanyam Jaishankar hold talks on the margins of the 18th East Asia Summit.
📍Jakarta, September 6
#RussiaIndia
🇷🇺🇮🇳 Foreign Minister Sergey Lavrov and Minister of External Affairs of India Dr. Subrahmanyam Jaishankar hold talks.
📍Cape Town, June 1, 2023
#RussiaIndia
🇷🇺🇮🇳 Foreign Minister Sergey Lavrov holds a meeting with Minister of External Affairs of the Republic of India Dr Subrahmanyam Jaishankar.
📍 New Delhi, March 1
#RussiaIndia
🇷🇺🇮🇳 Russia’s Foreign Minister Sergey Lavrov and Foreign Minister of India Dr. Subrahmanyam Jaishankar hold talks on the sidelines of the Shanghai Cooperation Organisation (#SCO) Heads of State Council meeting.
📍 Astana, July 3
#RussiaIndia
Embassy of Russia in India:
🇷🇺🇮🇳April 13 marks the 79th anniversary of diplomatic relations between Russia and India.
The status of a Special and Privileged Strategic Partnership reflects the scale and depth of Russia-India ties across the political, trade, economic, scientific, technological, educational and cultural spheres.
Flagship areas of bilateral cooperation include joint investment projects, the development of transport corridors, as well as collaboration in space exploration and nuclear energy. Among our foremost priorities are energy security and defence cooperation.
The dynamic growth of bilateral engagement at all levels, including business and interregional contacts, as well as record trade turnover, reflects our shared commitment to the steady further development of equal, trusting and mutually beneficial cooperation. Tourist flows are growing, while humanitarian exchanges continue to expand.
🤝Russia and India are bound by decades of fruitful and effective interstate cooperation, as well as by centuries of genuine friendship and civilisational dialogue.
☝️Our common task is to preserve and build upon this unique legacy.
#RussiaIndia#DruzhbaDosti