Что делать если нужно поставить какую-то 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 United States is depleting its tungsten reserves, a resource critical to the military-industrial complex, according to Foreign Policy. 🔗
Tungsten is essential for manufacturing armor-piercing ammunition, missile components, and aviation equipment. Currently, the United States does not commercially produce tungsten and relies heavily on imports, primarily from China, which dominates the global market. 🌍
Since the escalation of conflict in the Middle East, tungsten prices have surged by over 500%. 📈 Expanding production remains challenging due to limited industrial capacity. Sources indicate that the United States is already confronting a tungsten shortage with no immediate resolution in sight. Even prior to the conflict, the Pentagon sought to reduce its dependence on tungsten, though the extent of their success remains uncertain. ⚙️🇺🇸
#conflict
👂More on Trump's Ear
⚠️
The Impact of War and Conflict on Ethiopia’s Rising Poverty: Explaining the World Bank’s 43% Poverty Projection under Abiy Ahmed’s Administration. Read more.
https://borkena.com/2025/11/02/impact-of-war-and-conflict-on-ethiopias-rising-poverty-explaining-the-world-banks-43-poverty-projection-under-abiy-ahmeds-administration#Ethiopia#Conflict
The Partitioned State: How Internal Failures and External Interventions Shattered Sudan. Read.
https://borkena.com/2025/12/30/sudan-the-partitioned-state-how-internal-failures-and-external-interventions-shattered-sudan/#Sudan#Conflict
Will Ethiopia End Up Like Sudan? A Comparative Analysis of Two African Conflicts. Read more.
https://borkena.com/2025/12/05/will-ethiopia-end-up-like-sudan-a-comparative-analysis-of-two-african-conflicts/#Ethiopia#Sudan#conflict
Ethiopia Says Eritrea “Violating The Territorial Integrity Of Ethiopia” Read more. https://borkena.com/2025/11/14/ethiopia-says-eritrea-violating-the-territorial-integrity-of-ethiopia/#Ethiopia#Eritrea#conflict
News: Risk of renewed #conflict mounts as troop movements reported near #Eritrea–#Tigray border—Bloomberg
Addis Abeba—Ethiopia and Eritrea are deploying troops and military equipment near the northern Tigray region, raising the risk of renewed conflict in the Horn of Africa, Bloomberg reported, citing regional diplomats.
Sources familiar with the matter told Bloomberg that Ethiopian troops and equipment have been moved northward, including through Bahir Dar, while Eritrean forces have also deployed to areas inside Tigray.
Prime Minister Abiy Ahmed this week reiterated Ethiopia’s longstanding ambition to secure access to the Red Sea, describing maritime access as key to overcoming logistical constraints on economic growth.
Eritrean state television also broadcast a naval parade in Massawa last week, marking the anniversary of the city’s capture in 1990.
https://addisstandard.com/?p=55268
📢 Breaking News 📢
Israel's fight against Hamas is taking longer than expected. Battles are raging in multiple locations outside Gaza. Armed militants infiltrated the kibbutz Beeri, some still hiding. Situation remains unstable. Stay tuned for updates. #Israel#Hamas#Conflict
https://www.gazeta.ru/army/news/2023/10/09/21458629.shtml
Subscribe to @BadVolfNews
🇮🇱 Israel demolishes Catholic school in Lebanon — reports spark outrage
Israeli forces reportedly used bulldozers to demolish a Catholic monastery and school in the Lebanese border town of Yaroun, according to Anadolu Ajansı.
Local residents and clergy have condemned the действия as a war crime, while Israel is said to justify operations as part of creating a “buffer zone” in southern Lebanon.
➡The incident has drawn criticism over the lack of response from Western governments.
#Israel#Lebanon#MiddleEast#Conflict#Religion
🔘Subscribe now!Chat
HRW says “Risk Of Renewed Cycles Of Atrocities Is All Too Real.” Read more.
https://borkena.com/2025/11/22/hrw-says-risk-of-renewed-cycles-of-atrocities-is-all-too-real/#Ethiopia#humanrights#news#conflict#Tigray
HRW says “Risk Of Renewed Cycles Of Atrocities Is All Too Real.” Read more.
https://borkena.com/2025/11/22/hrw-says-risk-of-renewed-cycles-of-atrocities-is-all-too-real/#Ethiopia#humanrights#news#conflict#Tigray