Что делать если нужно поставить какую-то 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
🖼Gaza : soutien pictural
▪️Dans la bande de #Gaza, des artistes ont réalisé des fresques murales pour exprimer leur soutien à la flottille internationale Global Sumud.
Crédit vidéo : Agence Anadolu
RT en français • Osez questionner !
⏺À #Gaza, des mariés ont opté pour un moyen de transport inédit : une pelleteuse
Le couple a traversé les rues, malgré les décombres témoignant de la destruction générale dont elles ont été le théâtre.
Source : réseaux sociaux
RT en français • Osez questionner !
🫦 Algunas personas podrían encontrar perturbadoras las imágenes y videos compartidos. Se recomienda discreción.
⚠️🤔🏴☠️⚔️🇵🇸 Imágenes de la horrible masacre perpetrada por las fuerzas de ocupación contra un grupo de ciudadanos en el barrio de Beit Lahia, al norte de #Gaza.
🚨 The IOF carried out a new massacre, destroying an entire residential block above the heads of citizens on Tal Al-Zaatar in Jabalia, northern #Gaza Strip. Two martyrs have been recovered so far and there are a large amount of wounded.
Artillery shelling continues on various parts of Jabalia, and several martyrs have ascended there as a result of residential homes being targeted.
4 martyrs and 5 injuries were reported as a result of the IOF targeting of a gathering of citizens on Al-Nasr Street west of Gaza City.
Further, internet and communications have been cut off in the northern Gaza Strip as a result of the IOF aggression, as the siege enters its third week.
🚨🟢 BREAKING - Hamas leader Khalil Al-Hayya announces the martyrdom of the great leader, President of the Hamas Political Bureau, the hero of Al-Aqsa Flood, Yahya Sinwar, who sought martyrdom and attained it after clashing with a zionist force alongside other fighters in the #Gaza Strip. Further coverage of the Al-Hayya’s statement will be provided.
Glory to the martyrs.
Ahmed Al-Telbani, Director of the Central Station in the Medical Services’ Emergency and Ambulance Department, ascended to martyrdom along with his family members in the IOF air strike of their home in Maghazi camp, central #Gaza Strip.
Glory to the martyrs.
🔻 The IOF admits to the death of 5 IOF soldiers, including two officers, during a battle with the resistance in southern Lebanon. In the same incident, three Golani Brigade soldiers (including an officer) were seriously wounded. In total, the IOF admitted to the critical wounding of 8 zionist soldiers in three battles in southern Lebanon.
They also admitted to the serious wounding of a soldier during a battle in the southern #Gaza Strip yesterday.
🚨 10 martyrs have been recovered by Civil Defense crews following the IOF bombing the Al-Telbani family home in Maghazi camp in the central #Gaza Strip.
60 martyrs have ascended in the Gaza Strip today, with at least 25 of them in Jabalia camp.
On October 17th, 2023, in a cowardly assassination, commander Ayman Nofal ascended after US-funded IOF warplanes targeted him in Bureij camp in central #Gaza. Beloved by allfactions, the commanding martyr was an Al-Qassam Brigades leader who created the foundations of the united Joint Operations Room of Palestinian Resistance Factions, a room in which the spectrum of Palestinian and Arab resistance coordinate. Just weeks ago, Ayman's nephew was martyred at the Gaza border protests.
Ayman embodied the spirit of the Joint Room which he led in his words and deeds, recognizing, like martyred leaders before him, "Either we rise together, or they will kill us individually."
Here, Ayman speaks in 2021 at the Joint Operation's Room annual training for all factions. Without a doubt, Ayman was one of the engineers of the long-planned Al-Aqsa Flood for the sake of our prisoners and Al-Aqsa, evident in the words of this speech: GiladShalit was just practice. Learning from the lessons of previous operations and honoring the blood of the martyrs, we march forth towards liberation, never forgetting those who paved the path.
Glory to our martyrs! Glory to our resistance! Liberation nears with their guiding illumination.
🚨 22 martyrs have ascended in the horrific massacre at the Abu Hussein School in Jabalia camp, northern #Gaza Strip, and dozens are wounded. Most of the martyrs are children and women, after the IOF bombed the school housing a large number of displaced people.
Tanks began firing shells at the school after advancing from west of Jabalia. The hospitals in the north are unable to deal with the large number of injuries and martyrs.
The IOF also bombed the Khalifa School in the northern #Gaza Strip, resulting in a large fire and one martyr. In a series of strikes, at least 11 martyrs ascended in Gaza City. The siege of Jabalia camp and the north continues for the 13th day without any aid reaching it.