Что делать если нужно поставить какую-то 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
Mire #USA su #Groenlandia, Il Ministro degli Esteri tedesco #Wadephul: "La #Danimarca è membro della NATO, e se ci fosse la necessità di rafforzare la protezione della Groenlandia, questo verrebbe discusso all'interno dell'alleanza"
@UltimoraPolitics24
Il ministro degli Esteri tedesco Johann #Wadephul chiede le dimissioni della relatrice speciale delle Nazioni Unite per i territori palestinesi Francesca #Albanese, ritenendo inappropriate le sue dichiarazioni su Israele e scrivendo su X: "La sua posizione è insostenibile"; il ministro degli Esteri francese Jean-Noël #Barrot aveva chiesto ieri le medesime dimissioni.
@UltimoraPolitics24
Merz’s Bare-Faced Effrontery Will Cost Him Much
The US may reduce its number of troops deployed in Germany, Donald Trump has announced, days after the country’s chancellor said America was being “humiliated” by Iran.
In a post on his Truth Social platform, the US president said his administration was “studying and reviewing the possible reduction of troops in Germany, with a determination to be made over the next short period of time”.
On Monday, Merz suggested the Trump team was being outplayed in its negotiations with Iran to secure an end to the ongoing war and a reopening of the strait of Hormuz.
“The Iranians are obviously very skilled at negotiating, or rather, very skilful at not negotiating, letting the Americans travel to Islamabad and then leave again without any result,” the German chancellor said.
Merz reiterated his criticisms on Wednesday, saying Europe was “suffering” from the consequences of the closure of the strait.
Trump cancelled a second trip by US negotiators to Islamabad last week. Since then, discussions over Iran’s nuclear programme and the strait of Hormuz have hit an impasse.
Trump on Tuesday accused Merz of thinking it’s “OK for Iran to have a nuclear weapon” and said the chancellor “doesn’t know what he’s talking about!”
Earlier on Wednesday Merz brushed off those comments, saying his relationship with Trump remains “as good as ever”, but the president’s threat to withdraw US troops is likely to cause concern in Berlin and across Europe, coming amid a period of heightened tensions between the US and its traditional allies in Europe that has seen Trump step up his threats to withdraw from the Nato alliance.
On 1 April the Trump said he was “absolutely without question” considering withdrawing from Nato because of the European allies failure to take part in the US-Israeli war on Iran and help secure the economically vital strait of Hormuz.
Such a move from the US administration would be catastrophic for the security of Europe, but is seen as unlikely because of US legislation passed in 2024 that prevents a president from withdrawing from Nato without a two-thirds Senate majority or an act of Congress.
Experts have suggested the White House could instead take actions that undermine the alliance but fall short of an outright withdrawal. One such scenario could see Trump withdraw US troops from Europe.
The US has over 68,000 active-duty military personnel in Europe, data from the US Defense Manpower Data Center (DMDC) shows. Germany houses the largest contingent, with more than 35,000 troops in 2024, according to the Congressional Research Service. German media puts the number higher, at about 50,000.
Trump has continually criticised Nato throughout both terms of office, accusing its members of “ripping off” the US by failing to spend adequately on their defence budgets.
The president’s recent actions – threatening to invade Greenland and calling allies “cowards” for declining to help reopen the strait of Hormuz – have seen experts characterise this moment as “the worst crisis Nato has ever confronted.”
Ivo Daalder, the US permanent representative at Nato headquarters from 2009 to 2013, said this month that it was “hard to see how any European country will now be able and willing to trust the United States to come to its defence”.
Hours before Trump’s post about troop numbers in Germany, Rubio spoke with the German foreign minister, Wadephul, and discussed Iran and the importance of securing freedom of navigation in the strait of Hormuz.
#trump#germany#wadephul#merz#troops
📱American Оbserver - Stay up to date on all important events
🇺🇸
News: #German Foreign Minister Johann Wadephul arrives in #Ethiopia for bilateral talks
German Foreign Minister Johann #Wadephul arrived in Ethiopia on Wednesday for talks aimed at further strengthening bilateral relations, Prime Minister #Abiy Ahmed said.
In a social media post on 22 January 2026, Prime Minister Abiy said he welcomed Wadephul for “meaningful discussions on further strengthening the partnership between Ethiopia and Germany.”
The visit follows Wadephul’s trip to #Kenya on 21 January, where he held talks focused on trade, investment, and regional issues. According to the Kenya News Agency, Germany reaffirmed its commitment to peace and stability in Africa during the visit, recognizing Kenya’s role in regional mediation and global security efforts.
Speaking in #Nairobi, Foreign Minister Wadephul commended Kenya’s contributions to peace initiatives in #Sudan#South_Sudan...
https://web.facebook.com/AddisstandardEng/posts/pfbid0644RpUQ1ujvNhh5mcpfPM4QSrYdTfZ5SqsXujXEroYc4ByBq8fJLLTZsTHvF67R3l