Что делать если нужно поставить какую-то 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
🇷🇺🇦🇲 On April 1, President Vladimir Putin held talks at the Kremlin with Prime Minister of the Republic of Armenia Nikol Pashinyan, who arrived in Moscow on a working visit.
💬 President of Russia Vladimir Putin: Mr Pashinyan, friends,
We are delighted to welcome you in Moscow. Thank you very much for accepting our invitation and coming here.
We can see that domestic political processes in Armenia are gaining momentum, with elections approaching. In this context, I would like to emphasise several key points: such processes often become more intense during election campaigns, as is the case not only in Armenia, I believe, but also in Russia and other countries. However, this escalation must not be allowed to affect relations between Russia and Armenia.
We have discussed this many times. Russia and Armenia have special relationships which have evolved over centuries rather than decades. We are united by our common history as well as our cooperation to solve the challenges that we faced in years past. Crucially, we are also united by civilizational affinity. I have already told you this privately before, and I can say it publicly now: we are always in favour of anything that benefits the Armenian people, and you can always rely on it.
As for economic cooperation, it continues to develop at a solid pace. Trade reached approximately $11 billion the year before last, and amounted to $6.4 billion in 2025. <...>
We observe that there is an ongoing discussion in Armenia concerning the development of relations with the European Union. We remain entirely calm about this, understanding that each nation endeavours to maximise the advantages of cooperation with third countries. However, this must be transparent and articulated honestly, in advance, as it were, “on the shore,” beforehand.
Simultaneous membership in the Customs Union with the European Union and the #EAEU is impossible; it is simply untenable by definition. The issue is not even a political one; it is purely economic. <...>
There are also numerous other issues today, at this present moment. Perhaps years will pass, and we – the EAEU and the European Union – I hope this will eventually be the case, given that we reside on the same continent – will be able to resolve them. <...>
Now, regarding energy. I hope the situation will improve there as well. However, currently, as you are aware, energy prices, gas prices, for instance, in Europe exceed 600 dollars per 1,000 cubic metres, whereas Russia provides gas to Armenia at 177.5 per 1,000 cubic metres. The disparity is vast, the difference is substantial. <...>
Now, turning to security issues. Of course, the most sensitive issue to this day – and we recognise this, we discuss it often – is everything relating to #Karabakh. <...> But I think it is also clear that, after you recognised Karabakh as part of Azerbaijan in Prague in 2022, it simply became wholly inappropriate for the #CSTO to become involved in a process that had taken on an intra-Azerbaijani dimension. <...>
Incidentally, thanks to your efforts and those of the President of Azerbaijan, I believe you have now managed to stabilise relations. The US President has played an active role in this, and I understand transport links are being unfrozen, and so on. But I think we also need to draw a line under this matter. And it would be better if this did not become entangled in the domestic political process, especially during an election campaign.
<...>
Let me say again that, whatever happens, we in Russia will always be guided by what is best for the Armenian people. I have said this to you before, and I want to emphasise it once again.
🤝 And I would like to express my hope that, regardless of the outcome of the elections in Armenia, our shared commitment to building and strengthening #RussiaArmenia ties will continue.
Thank you.
Armenian PM Pashinyan Clashes with Passenger over Karabakh in Yerevan Metro
Armenian Prime Minister Nikol Pashinyan argued with a Karabakh resident in Yerevan metro, accused of surrendering the region to Azerbaijan. Pashinyan defended government efforts to preserve Karabakh’s population, citing significant budget allocations. He urged not to blame him for betrayal: “Why didn’t you stay? Don’t say I surrendered Karabakh.” This incident highlights ongoing tensions over the disputed region’s future.
#Armenia#Karabakh#Pashinyan#InternationalNews
The main news of Russia and the world ishere.
🇷🇺🇦🇲 On April 1, President Vladimir Putin held talks at the Kremlin with Prime Minister of the Republic of Armenia Nikol Pashinyan, who arrived in Moscow on a working visit.
💬 President of Russia Vladimir Putin: Mr Pashinyan, friends,
We are delighted to welcome you in Moscow. Thank you very much for accepting our invitation and coming here.
We can see that domestic political processes in Armenia are gaining momentum, with elections approaching. In this context, I would like to emphasise several key points: such processes often become more intense during election campaigns, as is the case not only in Armenia, I believe, but also in Russia and other countries. However, this escalation must not be allowed to affect relations between Russia and Armenia.
We have discussed this many times. Russia and Armenia have special relationships which have evolved over centuries rather than decades. We are united by our common history as well as our cooperation to solve the challenges that we faced in years past. Crucially, we are also united by civilizational affinity. I have already told you this privately before, and I can say it publicly now: we are always in favour of anything that benefits the Armenian people, and you can always rely on it.
As for economic cooperation, it continues to develop at a solid pace. Trade reached approximately $11 billion the year before last, and amounted to $6.4 billion in 2025. <...>
We observe that there is an ongoing discussion in Armenia concerning the development of relations with the European Union. We remain entirely calm about this, understanding that each nation endeavours to maximise the advantages of cooperation with third countries. However, this must be transparent and articulated honestly, in advance, as it were, “on the shore,” beforehand.
Simultaneous membership in the Customs Union with the European Union and the #EAEU is impossible; it is simply untenable by definition. The issue is not even a political one; it is purely economic. <...>
There are also numerous other issues today, at this present moment. Perhaps years will pass, and we – the EAEU and the European Union – I hope this will eventually be the case, given that we reside on the same continent – will be able to resolve them. <...>
Now, regarding energy. I hope the situation will improve there as well. However, currently, as you are aware, energy prices, gas prices, for instance, in Europe exceed 600 dollars per 1,000 cubic metres, whereas Russia provides gas to Armenia at 177.5 per 1,000 cubic metres. The disparity is vast, the difference is substantial. <...>
Now, turning to security issues. Of course, the most sensitive issue to this day – and we recognise this, we discuss it often – is everything relating to #Karabakh. <...> But I think it is also clear that, after you recognised Karabakh as part of Azerbaijan in Prague in 2022, it simply became wholly inappropriate for the #CSTO to become involved in a process that had taken on an intra-Azerbaijani dimension. <...>
Incidentally, thanks to your efforts and those of the President of Azerbaijan, I believe you have now managed to stabilise relations. The US President has played an active role in this, and I understand transport links are being unfrozen, and so on. But I think we also need to draw a line under this matter. And it would be better if this did not become entangled in the domestic political process, especially during an election campaign.
<...>
Let me say again that, whatever happens, we in Russia will always be guided by what is best for the Armenian people. I have said this to you before, and I want to emphasise it once again.
🤝 And I would like to express my hope that, regardless of the outcome of the elections in Armenia, our shared commitment to building and strengthening #RussiaArmenia ties will continue.
Thank you.
⚡️Советую евродепутатам, голосовавшим за предвзятую резолюцию против #Азербайджан’а, посмотреть мой фильм про разрушенную церковь в Ходжавенде. Сразу становится ясно, как #Армения за годы оккупации разрушила не только мусульманское, но и христианское наследие в #Карабах’е👇
https://youtu.be/cyacJfkSEiA
💡 I advise the MEPs who voted for the biased resolution against #Azerbaijan to watch my film about the destroyed church in Khojavend. It immediately becomes clear how during the years of occupation #Armenia destroyed not only the Muslim, but also the Christian heritage in #Karabakh👇
https://youtu.be/cyacJfkSEiA
🇦🇿#Aghdam before and after the #armenian occupation!
Imaret complex of the #Karabakh khans in #Azerbaijan’s Aghdam district had been vandalized by the Armenians
«What’s happened in #Karabakh is a part of global justice» - world famous photographer Reza Deghati
#KarabakhisAzerbaijan#Shusha#RezaDeghati#Azerbaijan#Armenia