Что делать если нужно поставить какую-то 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 way the United States has dealt with its ally, the #SDF, in #Syria is a wake-up call for all countries that believe they are strategic allies of the United States."
https://x.com/Mr_Salarosh/status/2015329233464447232
N.E #Syria : Field developments indicate that al-Jolani terrorist regime is not adhering to the declared ceasefire, despite the #SDF confirming its commitment to it.
Updates from the #SDF:
📌8:40 PM (Damascus time):
The town of Zarkan has been under heavy artillery shelling by Damascus factions for about half an hour, coinciding with Turkish drones flying over the area. Damage and casualty figures are still being assessed.
📌9:20 PM (Damascus time):
Damascus factions launched an attack using heavy weapons on the village of Tal Baroud, located on the Tal Abyad–Hasakah road, south of Hasakah.
Pres della Rep di #Turchia: "L'accordo tra le #SDF e il governo centrale servirà a garantire più sicurezza in #Siria. Riteniamo che ogni sforzo per liberare la Siria dal terrorismo sia un passo nella giusta direzione".
In #Siria sono ancora in corso gli scontri tra le Forze Democratiche Siriane, #SDF e le bande jihadiste sostenute dalla #Turchia. Riferiscono le SDF: "Uccisi 365 jihadisti, morti 81 nostri militanti, uccisi 47 civili tra cui 2 giornalisti".
Al-Hol Camp: Pro-alJolani media outlets have launched a campaign promoting the narrative that #ISIS detainees in al-Hol camp are "victims."
Since yesterday, pro–alJolani media have been conducting interviews with ISIS detainees in al-Hol camp, highlighting their claimed "suffering" and portraying them as having been wronged by the Syrian Democratic Forces (#SDF).
These interviews reveal that the camp houses men as well, contradicting the commonly promoted claim that it contains only women and children.
This style of coverage raises serious questions and suggests preparations to justify the release of some detainees, while ignoring their responsibility for some of the most brutal terrorist crimes in modern history, crimes rivaled only by those committed by Abu Mohammad al-Jolani himself.
Previously, a member of al-Jolani's government, Nour al-Din al-Baba, admitted that the perpetrators of the June 2025 suicide bombing targeting the Mar Elias Church in Damascus had come from al-Hol camp, exploiting the chaos following the fall of the former regime to escape the camp and reach Damascus. This raises the question: why is al-Jolani’s media now attempting to whitewash their image?
At the end of one circulating video showing al-Jolani's militias smuggling residents out of al-Hol camp, a child is heard asking one of the militants: “Do you have weapons?”, underscoring that this is a dangerous extremist group posing a serious threat to Syrian society and beyond.
Additionally, Saudi channel Al-Hadath aired footage from the camp showing an angry ISIS detainee demanding that the Syrian state hold UNHCR staff accountable.
#MazloumAbdi, comandante generale delle Forze Democratiche Siriane, #SDF; "Da due mesi siamo in contatto diretto con la #Turchia. Posso incontrare di persona il Presidente della Repubblica di Turchia".
#MazloumAbdi, comandante generale delle Forze Democratiche Siriane, #SDF: "Il Presidente della Repubblica deve identificare i responsabili del pogrom in corso contro gli aleviti. Sono coinvolte le formazioni paramilitari sostenute dalla #Turchia".
#Aleppo: Footage reveals the aftermath of shelling by alJolani-led/ #HTS-led regime forces targeting the Sheikh Maqsoud neighborhood in Aleppo.
Several shells also landed in the adjacent Al-Midan neighborhood due to indiscriminate attacks on residential areas.
Local media and the Saudi channel "Al-Hadath" falsely claimed that the shelling was carried out by the #SDF, despite footage clearly showing regime forces themselves using all types of artillery.
It should be emphasized that the SDF has no presence in Aleppo, having withdrawn all heavy weapons and personnel under the March 10 agreement. The only forces remaining in Sheikh Maqsoud and Al-Ashrafiyah are the Asayish units, which serve solely as internal security.
#MazloumAbdi, il comandante delle Forze Democratiche Siriane, #SDF e il Presidente della Repubblica di #Siria hanno trovato un accordo per l'integrazione all'esercito siriano.
#MazloumAbdi, comandante delle #SDF: “In #Siria ci sarà un cambiamento di base, non centralizzato. Tutti i popoli avranno un ruolo. Siamo in contatto diretto con la #Turchia e crediamo che possa contribuire positivamente.”
Oggi #Jolani in #Turchia, prima di partire: "Le Forze Democratiche Siriane, #SDF, accettano di aderire all'esercito ma ci sono dei disaccordi ancora da sistemare".