Что делать если нужно поставить какую-то 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
🇲🇿#Mozambique: IS-Mozambique (ISMP, Islamic State in Mozambique) released a video today claiming responsibility for an attack last Sunday targeting Mozambican military bases in the Katuba and Namapo areas of Cabo Delgado in the northern part of the country.
As a result of the attacks, it is reported that nine Mozambican soldiers were killed. The militants also posted footage showing weapon caches and equipment they captured from the bases.
(via @BrantPhilip_ on X)
⚡️Russia's EMERCOM:
On March 19, a special flight of Russia's EMERCOM delivered humanitarian aid to the Republic of #Mozambique.
By decision of Russia's President Vladimir Putin, following instructions from the Government of Russia and on the orders of EMERCOM Head Alexander Kurenkov, around 29 tonnes of humanitarian cargo were transported from Moscow.
🛬 An Il-76 aircraft delivered food, essential supplies, as well as tents and blankets for flood-affected communities in the African republic.
#RussiaHelps
The struggle for water in Mozambique's unstable north
Aid agencies warn that a shortage of safe water, poor sanitation and inadequate medical services are a looming threat for the communities in Mozambique's Cabo Delgado province
#News#Reuters#Mozambique#RedCross
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
#RussiaHelps
💬Maria Zakharova: OnDecember 17 inMaputo (#Mozambique) and December 18 inLusaka (#Zambia), official ceremonies marking the delivery of Russian food assistance were held, attended by the Russian Ambassadors to these countries.
🇲🇿 Mozambique received 70 tonnes of vitamin-fortified sunflower oil for those in need.
🇿🇲 Zambia received a similar shipment of 93 tonnes, as well as 648 tonnes of yellow split peas.
These humanitarian deliveries were carried out through the UN World Food Programme, funded by Russia’s voluntary contribution for African countries, which amounts to USD 10 million annually.
Humanitarian assistance is an integral part of Russia’s support for its partners on the African continent, primarily aimed at helping the most vulnerable groups.
🇷🇺 Russia will continue to contribute to addressing Africa’s socio-economic challenges, using both bilateral assistance mechanisms and the potential of relevant international organizations.
(Excerpt from Russian MFA Spokeswoman Maria Zakharova's weekly briefing on December 26)
#Italia y su desarrollo imperialista a cuenta del #gas en #África. Ahora #Mozambique
https://www.eleconomista.es/energia/noticias/12492596/10/23/los-planes-de-italia-para-el-gas-natural-pasan-por-coral-field-un-nuevo-yacimiento-en-mozambique.html
Russia and Mozambique may expand energy cooperation
During a visit to Moscow, Mozambique Foreign Minister Maria Manuela dos Santos Lucas said that the country views Russia as a strategic partner in the development of the oil and gas sector.
For Mozambique, which has the sixth largest natural gas reserves in Africa (about 100 trillion cubic feet), partnership with Russia is indeed of strategic value.
Russian companies offer not only investments, but also unique competencies in the development of offshore fields, construction of gas transportation infrastructure and training of qualified personnel. Today, about 40% of Mozambican students in the Russian Federation are studying in specialties needed in the oil and gas sector.
Despite Rosneft's withdrawal from the Mozambique LNG project in 2022, Russian companies remain interested in the region. In particular, Gazprom continues to explore the possibility of working on the Mozambican shelf.
According to experts, there are several key vectors of cooperation between the parties. This could be the creation of an LNG cluster using Russian technologies, joint projects for gasification of Mozambique regions, as well as the development of educational programs for training personnel.
#AREA#Africa#Russia#RussiaAfrica#energy#Mozambique