Что делать если нужно поставить какую-то 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
🚨 Zionist soldiers are documented hovering over a child they shot in Al-Aroub camp, #AlKhalil after they obstructed medical crews from reaching him.
Two other children have also been wounded by zionist bullets in the camp.
24-year-old prisoner Afnan Abu Hussein was released on a financial bail of 5,000 shekels on October 14 after being arrested the day prior from her home in the town of Bani Naim, #AlKhalil.
Afnan, who is in her ninth month of pregnancy (with a scheduled caesarean section on 16/10) and is a mother to a two-year-old child was beaten by the IOF in her home before they detained her. They abducted her before she was able to wear her hijab. She described the terrible conditions she experienced during her detention:
"They provoked me in the worst ways; it was psychological torture for me. They filmed me on TikTok while I was tied with shackles to the bed, and they danced around me. I would ask for a cup of water, after two days of no eating or drinking, and they would throw it in front of me; as a result, I became dehydrated and the water dried up for the baby. They didn't give me any medical treatment."
During her detention, the IOF also forced her to sign a paper which says she is responsible in the case of the death of her baby because she refused to give birth in an occupation hospital.
"Between us and them are mountains of corpses, rivers of hatred, blood, and blood, and blood, wailing, and a long revenge."
The ancient words repeated by our leaders, the Lion of the Den Mishal Al-Baghdadi and NidalKhazem, are present at the event honoring the second anniversary of martyr Nizar Banat's assassination by the traitorous Palestinian Authority in #AlKhalil.
Beyond the Envelope: Towards Al-Quds:
Under the cover and support of rocket fire, the resistance began a new and large incursion by land, air, and sea into occupied Palestine about three hours ago:
- Paratroopers have reportedly landed in "Netivot."
- Commandos of the resistance's naval units have set foot in IOF naval bases near occupied Asqalan and are engaged in fierce clashes.
- A large number of fighters stormed settlements with vehicles, taking over Route 232 and making their way deeper and deeper into the occupied interior.
Meanwhile, shooting operations and confrontations do not stop in the West Bank. Hezbollah has targeted IOF posts in occupied Shebaa Farms. An operation in Alexandria, Egypt led to the killing two zionists. One million settlers are leaving the entity, and thousands are fleeing settlements.
The temporary entity has declared a state of war. Over 100 settlers have been captured in Gaza, yet the IOF continues to indiscriminately bomb the Strip. At least 700 settlers have been killed, as many in two days as in three years of the Second Intifada.
Liberating land in real time, the resistance is closing in on the West Bank, at the door of "Kiryat Arba" in #AlKhalil. The resistance is a mere 10 kilometers away from splitting the zionist entity in two.
Free our Lions!
Despite the Palestinian Authority courts deciding to release him, the traitorous Palestinian Authority continues to kidnap the wanted resistance fighter, a Lion of the Den and Al-Qassam Brigades member, Musab Shtayyeh. Musab has been tortured and held in solitary confinement by the PA since the moment of his arrest. Musab was a strong link between Gaza and Nablus; the PA criminalizes his righteous resistance for the sake of the people they claim to represent because they work hand-in-hand with the zionist enemy.
The wanted resistance fighter and Al-Qassam Brigades member Musa Attallah has been kidnapped by the "Authority" for 135 days today.
The PA's tyranny knows no bounds, as it has also kidnapped one of its own officers, Emad Odeh. He has been held for 211 days as of today, simply for opening fire against a colonial settler as he was being attacked by them. Emad went on hunger strike in April.
The traitorous PA attacks Palestinians, doing the bidding of the zionist enemy. In the last few weeks, they have used undercover forces to arrest student activists and freed prisoners, to burn their cars, and open fire on the families of martyrs and prisoners. Following a large campaign of arrests in #AlKhalil, a number of students have been held for over a week. Two prisoners kidnapped by the PA are on their 9th day of hunger strike: Ismail Abu Shkeidem and Abdullah Al-Sous. Just a few days ago, its forces opened fire on mourners of resistance leader and martyr Khader Adnan, a figure that they repeatedly attacked in his life.
The list of similar cases goes on... Khader Adnan, Basil Al-Araj, Nizar Banat, Ahmed Sa'adat. The PA is simply a servant of zionism, and in the words of Basil, it "participates in our annihilation."
🚨 The IOF arrested 6 children during a raid on the town of Beit Ummar, north of #AlKhalil, according to local sources.
Separately, the Palestine Red Crescent Society reported that medical teams are treating a 21-year-old man who sustained gunshot wounds to the thigh and back from "israeli" occupation forces fire in Birzeit, north of #Ramallah.
🚨 IOF units are conducting a widespread campaign of raids and incursions across occupied Palestine, with operations concentrated in #Nablus, #Qalqilya, and #AlKhalil.
Concurrently, armed settlers are launching violent assaults with live fire against residential areas in the vicinity of Al-Arroub camp. Settler provocations are also reported across the Nablus district.
🚨 IOF units are conducting a widespread campaign of raids and incursions across occupied Palestine, with operations concentrated in #Nablus, #Qalqilya, and #AlKhalil.
Concurrently, armed settlers are launching violent assaults with live fire against residential areas in the vicinity of Al-Arroub camp. Settler provocations are also reported across the Nablus district.
🚨Summary of settler attacks in the West Bank over the past 24 hours:
• A settler attempted to run over a Palestinian woman near Al-Minya village, east of #Bethlehem.
• Settlers uprooted a large number of olive trees in the Wadi Musa area of Turmus Ayya, north of #Ramallah.
• Settlers attempted to block farmers from plowing their lands in the plains of Turmus Ayya.
• Settlers erected a tent near citizens' homes by the Carmelo roundabout near Al-Taybeh village, east of #Ramallah.
• Settlers released livestock in the vicinity of Palestinian homes in Susya village, Masafer Yatta, south of #AlKhalil.
• Settlers stormed Kafr Malik village, northeast of #Ramallah.
• Settlers attacked farmers and blocked access to their lands in the Ghuraba area, northwest of Sinjil village, north of #Ramallah.
• Settlers cut down and uprooted 400 centuries-old olive trees in the lands of Qusra, south of #Nablus.
• Settlers released livestock onto farmers' lands in Khirbet Al-Tawil, east of Aqraba, south of #Nablus.
🚨Summary of settler attacks in the West Bank over the past 24 hours:
• A settler attempted to run over a Palestinian woman near Al-Minya village, east of #Bethlehem.
• Settlers uprooted a large number of olive trees in the Wadi Musa area of Turmus Ayya, north of #Ramallah.
• Settlers attempted to block farmers from plowing their lands in the plains of Turmus Ayya.
• Settlers erected a tent near citizens' homes by the Carmelo roundabout near Al-Taybeh village, east of #Ramallah.
• Settlers released livestock in the vicinity of Palestinian homes in Susya village, Masafer Yatta, south of #AlKhalil.
• Settlers stormed Kafr Malik village, northeast of #Ramallah.
• Settlers attacked farmers and blocked access to their lands in the Ghuraba area, northwest of Sinjil village, north of #Ramallah.
• Settlers cut down and uprooted 400 centuries-old olive trees in the lands of Qusra, south of #Nablus.…
🚨 The IOF and armed settlers conducted a series of aggressions across the West Bank today:
Armed settlers attacked farmers in the village of Al-Mughayyir in #Ramallah and prevented them from harvesting olives. (media 1,2) Settlers also cut down olive trees in the village of Yasuf, east of #Salfit (media 3,4).
The IOF invaded the town of Beita, south of #Nablus, where confrontations erupted between resistance youth and the zionist forces. (media 5,6,7).
The IOF fired live bullets heavily at Palestinian homes at the entrance of Al-Arroub refugee camp, north of #AlKhalil. (media 8,9)
The IOF invaded Shufat refugee camp in #AlQuds. (media 10)