Что делать если нужно поставить какую-то 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
#Sudan’s Blue Nile displacement reaches 73,000 after #Kurmuk attack
Activists said on Thursday that approximately 73,000 people have fled Al-Kurmuk in Sudan’s Blue Nile region following attacks by the Rapid Support Forces (#RSF).
The RSF and the Sudan People’s Liberation Movement-North (#SPLM-N) led by Abdelaziz al-Hilu seized the border town on March 24. The offensive has sparked accusations that Ethiopia facilitated the attack from its territory.
The Blue Nile Humanitarian Emergency Room stated that according to data from the United Nations Office for the Coordination of Humanitarian Affairs (OCHA), 73,406 displaced people have arrived in Ed Damazin and surrounding areas.
Most of those fleeing the violence are women and children. The group described the humanitarian situation as extremely harsh, reflecting a deep tragedy for the local population.
Displaced families are reportedly facing a fragile reality characterized by acute shortages of food and clean.......
https://sudantribune.com/article/312121
News: #Sudan’s army recaptures key area near #Ethiopian border from RSF
Sudanese army forces say they have recaptured the Al-Sillik area in Blue Nile state, near the border with Ethiopia, from the paramilitary Rapid Support Forces (#RSF), following heavy fighting over the weekend.
In a statement issued on Monday and cited by Anadolu News Agency, the Sudanese Armed Forces’ (#SAF) 4th Infantry Division said its troops regained control of Al-Sillik “after a well-planned military operation,” claiming the offensive routed RSF fighters and inflicted heavy losses in both lives and equipment.
The army also said the clashes affected RSF allies from the Sudan People’s Liberation Movement–North (#SPLM-N), led by Abdel Aziz al-Hilu.
Read more: https://addisstandard.com/?p=54782
News: #Sudan says RSF, SPLM-N attack Blue Nile region from #South_Sudan
The Rapid Support Forces (#RSF) and the Sudan People’s Liberation Movement–North (#SPLM-N) launched a large-scale attack on Sudan’s #Blue_Nile region from South Sudanese territory on Sunday, Sudan Tribune reported, citing Sudanese government sources.
The attack in Sudan’s Blue Nile region, a direct neighbor to #Ethiopia, targeted Al-Sillik, #Milkan, and other locations in Bau County, with the army’s 4th Infantry Division reportedly engaged in fierce battles to repel what officials described as “foreign aggression,” Sudan Tribune reports indicate, as sources told it.
A senior government official accused South Sudan of allowing its territory to be used for training and receiving military equipment for the attacking forces. Widespread civilian displacement toward safer areas within Bau has occurred, the official said.
Read more: https://addisstandard.com/?p=54772
#Sudanese army evacuates hundreds as drone strikes intensify near #Ethiopian border
Sudanese army trucks evacuated hundreds of civilians from the strategic border town of #Kurmuk on Saturday, as an escalation in drone strikes by paramilitary and rebel forces opened a volatile new front in the country’s internal conflict.
The displaced residents arrived in #Ed_Damazin, the capital of the #Blue_Nile region in Sudan’s far southeast, following two days of intensified aerial bombardment.
Local officials reported that a combined force of the Rapid Support Forces (#RSF) and the Sudan People’s Liberation Movement-North (#SPLM-N), led by Joseph Touka, has been targeting residential neighbourhoods and infrastructure.
“The attacks forced citizens to flee toward Ed Damazin once again,” said Kurmuk Commissioner Abdel Ati al-Faki. He noted that approximately 80 families, totalling some 300 people, reached the capital on Saturday, joining nearly 1,900 others who have arrived...
https://sudantribune.com/article/311214
News: RSF claims capture of #Kurmuk near #Ethiopia border amid escalating tensions
#Sudan’s paramilitary Rapid Support Forces (#RSF) has claimed it captured the strategic town of Kurmuk in #Blue_Nile State following intense fighting with the Sudanese Armed Forces (#SAF), according to a report by Xinhua.
In a statement, the RSF said its forces, alongside the Sudan People’s Liberation Movement-North (#SPLM-N), had taken control of Kurmuk and surrounding areas after what it described as “fierce” battles.
Kurmuk, located near the Ethiopian border, is considered a strategic corridor linking Blue Nile and #Sinnar states and providing access to key infrastructure, including the Al-Roseires Dam.
Analysts cited by Xinhua said control of the town could shift regional dynamics and affect cross-border movements.
As previously reported by Sudan Tribune, a Sudanese government official claimed that fighters linked to the RSF and SPLM-N entered Blue Nile through......
Read more: https://addisstandard.com/?p=56050
News: #Sudanese officials accuses #Ethiopia of aiding rebel assault on Kurmuk
Sudanese authorities have accused Ethiopia of facilitating a renewed offensive by allied rebel forces on the strategic border town of #Kurmuk in #Blue_Nile state, according to a report by Sudan Tribune.
A Sudanese government official, cited by the outlet, alleged that Ethiopia “sponsored” the assault by allowing fighters linked to the Rapid Support Forces (#RSF) and the Sudan People’s Liberation Movement-North (#SPLM-N) to operate through its territory.
The source claimed combat vehicles moved from #Assosa in Ethiopia toward border areas before launching the attack.
Fighting has intensified around Kurmuk, with clashes reported across multiple fronts.
The accusations come amid earlier claims reported by Reuters in February that Ethiopia is hosting a training camp for RSF-linked fighters in the #Benishangul-Gumuz region near the Sudan border.
Sudanese officials have.......
Read more: https://addisstandard.com/?p=56021
News: #Sudanese official alleges #Ethiopia facilitated RSF, SPLM-N attacks in Blue Nile
Ethiopia has been accused of facilitating the movement of attacking forces into Sudan’s #Blue_Nile region, according to a report by Sudan Tribune.
The Rapid Support Forces (#RSF) and the Sudan People’s Liberation Movement-North (#SPLM-N) reportedly launched coordinated attacks on multiple army positions on Tuesday, seizing the strategic town of #Deim Mansour in #Kurmuk County.
Video and social media posts from the SPLM-N claim that combat vehicles, tanks, and drones were captured during the assault.
A high-ranking Sudanese government official told Sudan Tribune that the RSF and SPLM-N forces entered Sudan from Ethiopian territory, specifically from the #Benishangul-Gumuz region,...
According to a report by AFP on Wednesday, Sudan’s paramilitary forces have advanced toward army positions near the country’s southeastern border with Ethiopia. The advance was reported....
Read more: https://addisstandard.com/?p=54985
#Sudan army says it seized two areas in #Blue_Nile region
The Sudanese army said on Thursday it had seized control of two areas in the Blue Nile region, marking a significant advance in the #southeastern province where fighting has escalated since January.
The 4th Infantry Division, the army’s primary command in the region, said in a statement that its troops and allied forces “cleared” #Jort East and the #Ballamo camp following decisive battles against paramilitary and rebel groups.
The southern and western sectors of the Blue Nile province have seen a surge in violence this year. The army is currently engaged in a conflict against an alliance of the Rapid Support Forces (#RSF) and the Sudan People’s Liberation Movement-North (#SPLM-N) led by Joseph Touka.
Military officials stated the operation was part of a broader campaign to secure strategic locations in the southern sector.
https://sudantribune.com/article/311706