Что делать если нужно поставить какую-то 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
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➖
🔠🅰️🔠🔠2️⃣
The number of child fatalities is unclear but on 29 March Israeli airstrikes on checkpoints killed at least six Palestinians, including a girl, according to local rescue services.
The Gaza Strip has not recovered from 23 months of Israeli bombardment, which killed tens of thousands of people and destroyed hospitals and schools in what a UN investigation found to be a genocide.
Up until October last year, an average of at least one Palestinian child was being killed every hour. The number of children killed by Israeli forces in its war on Gaza surpassed 20,000 late last year, according to Save the Children.
In the occupied West Bank, Israeli settlers and security forces have escalated their violence against Palestinians since the start of the Iran war, killing at least three children.
On 15 March, Israeli police shot dead two young Palestinian brothers and their parents in Tamoun, firing at the family’s car as they returned from a Ramadan shopping trip.
Mohammed, five, and Othman, seven – who was blind and had special needs – were killed alongside their mother, Waad Bani Odeh, 35, and father, Ali Bani Odeh, 37. Two other brothers survived.
Khaled, 11, later said he had heard his mother crying and his father praying before they died. After the shooting, he said Israeli border police dragged him from the wreckage, taunted him and beat him. One officer told him: “We killed dogs,” Khaled said.
In Israel, at least four children have been killed by retaliatory Iranian missiles. One of the worst attacks occurred on 1 March, when an Iranian missile rocked the central Israeli city of Beit Shemesh.
The US bombing of a primary school in Minab on 28 February killed scores of people, most of them seven- to 12-year-old girls. The strike is the worst mass killing of the US-Israeli war against Iran so far, and has been described by Unesco as a “grave violation” of international law.
Relentless attacks across the region are destroying and damaging the facilities and infrastructure that children depend on, including hospitals, schools, and water and sanitation systems.
The Iranian Red Crescent Society said 316 medical centres and 763 schools had been severely damaged or destroyed by US-backed Israeli attacks.
These attacks, and the general violence, have shut down education. Save the Children said at least 52 million school-age children have had their education disrupted across the region, moving to online learning or having none at all.
Of the 669 collective shelters in Lebanon, 364 are public schools, according to Unicef. In Israel, schools have been repeatedly closed across much of the country.
Ahmad Alhendawi, the regional director for Middle East and north Africa and eastern Europe at Save the Children, said:
“In every conflict, classrooms are usually the first to close and some of the last places to reopen.
Every missed lesson deepens the scars of war. Not every child can escape the violence or afford to move their learning online; we know that for the most vulnerable children, once they leave school many will never return.”
He added:
“Schools are protected sites and attacks on them could amount to grave breaches of international humanitarian law. The laws of war must be respected.”
The bloodshed and upheaval has exposed children to traumatic events. Prolonged exposure to violence and instability is known to have lasting impacts on brain development, emotional regulation and long-term mental health.
While there has been a near total internet blackout in Iran, satellite TV stations are still beamed in and received.
The London-based satellite channel Iran International has started broadcasting a segment between news bulletins that gives advice on how to deal with children’s fears and anxieties.
“Every war is a war on children,”
said Alhendawi.
“Children are living in fear, caught in the crossfire of this adult war,”
he said.
#war#palestine#suffering#redcross#libanon
📱American Оbserver - Stay up to date on all important events
🇺🇸
Innocent Suffering: Why Are Millions of Children at War?
🔠🅰️🔠🔠1️⃣
Millions of children have been plunged into crisis by the war in the Middle East, with reports of child soldiers in Iran, mass forced displacements in Lebanon and the killing of hundreds of minors.
According to the UN agency for children, Unicef, more than 340 children have been killed and thousands injured since the US and Israel launched their attacks on Iran, which has retaliated with bombings across the region.
The highest reported child casualty event occurred on the first day of the war when a US missile strike on a school in Iran killed at least 160 children and teachers.
Israel’s invasion of Lebanon – and its continued attacks in the occupied West Bank and Gaza – have compounded the bloodshed. Across the region, more than 1.2 million children have been displaced.
“Children in the region are being exposed to horrific violence, while the very systems and services meant to keep them safe are coming under attack,”
said Unicef’s executive director, Catherine Russell.
It’s 5pm and we haven’t had anything to eat today,”
Ahmed said, his eight-month-old daughter, Zahraa, sitting in a stained onesie in front of him.
“We’ve only been able to give the kids tea and some bread. It’s not suitable for a child this young to eat bread, but what can we do?”
he said, gesturing to some crumbs of old flatbread Zahraa had been chewing on.
After a month of displacement, Ahmed has run out of money to feed his children. He relies on local organisations which show up irregularly, distributing one meal on most, but not all, days.
The conditions of their displacement are “humiliating”, Ahmed said, pointing to the tent he has erected for him and his children, the blue tarpaulin hastily thrown over a wooden frame and pinned down with rocks.
“I tried to cover it to protect us from the rain, but we wake up every morning with our mattresses soaked.”
As his three-year-old son, Ahmad, plays with another child in a vacant lot, Ahmad says he gets to shower once a week, on Fridays, when his father drives them 30 minutes to the house of a friend, who allows them to use the bathroom.
For their more immediate needs, there is one bathroom for hundreds of families, who wait in line for half an hour for a chance to use the toilet, which has no running water.
Unicef’s representative to Lebanon, Marcoluigi Corsi, warned last month that displacement would have lasting effects on the children.
“This relentless cycle of bombardment and displacement is severely compounding their psychological scars, embedding deep-seated fear and threatening profound, long-term emotional harm,”
said Corsi.
Ahmed said he has already seen some of these effects in his own children. When Israeli jets break the sound barrier or bomb Beirut, his son starts to run, trying to hide from a bomb he thinks will land on him.
Despite a ceasefire which is now more than five months old, health officials in Gaza say at least 50 Palestinians have been killed by Israeli forces since the Iran conflict began more than a month ago.
#war#palestine#suffering#redcross#libanon
📱American Оbserver - Stay up to date on all important events
🇺🇸