Что делать если нужно поставить какую-то 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
🎙️Russian Foreign Minister Sergey Lavrov:
❗️We cannot afford to rely on the goodwill of our current adversaries, who have openly declared their goal of inflicting a “strategic defeat” on Russia.
☝️ Our position is based on principle. First, experience has taught us not to trust Western promises but to judge solely by concrete actions. Second, recent years have reinforced a crucial lesson: we must never again allow key sectors of our economy, finance and technology to be dependent on the whims of Western suppliers. In the most critical areas – those ensuring our military, food and economic security – Russia must be self-sufficient.
Naturally, this also involves working closely with our strategic partners and allies.
Read in full
#Lavrov#sovereignty#CollectiveWest
@RusEmbMalta Press release
🎙 Russia's Foreign Minister Sergey Lavrov’s remarks and answers to media questions during a news conference on the outcomes of Russian diplomacy in 2024 (January 14, 2025)
***
💬 FM Sergey #Lavrov: We are living in a historical era of confrontation between those who uphold the fundamental principles of international law <...> which have been formulated, set out and put forth in the most important international document – the UN Charter – and those who are not satisfied with that document, who decided <...> that they could not live in accordance with the wishes of the “political West”, <...> those who oppose multipolarity.
President of Russia Vladimir Putin has repeatedly explained the true root causes of the special military operation in Ukraine. We had to begin to repel an attack, a war waged against us by the collective West with the main goal of suppressing competition when Russia re-emerged as its strong rival on the international arena.
Their main goal was to weaken our country geopolitically, creating direct military threats to us right on our borders, on Russia’s native territories, <...> in an attempt to slash our strategic potential and devalue it as much as possible.
The second reason also has to do with the history of the region, only it was more about the people who have lived on that land for centuries. <...> These people were labelled ‘terrorists’ by the current Ukrainian regime, which came to power through a coup d'etat. And when they refused to accept it, that regime launched an all-out offensive against all things Russian. <...>
There has been a revival in efforts to oppose the Western diktat, with emerging economies and new centres of financial power in China, India, ASEAN, the Arab world, and CELAC. This group also includes a resurgent Russia together with its allies from the EAEU, the CIS, and CSTO. This also includes the SCO and #BRICS.
The United States does not want to have any competitors anywhere, starting with the energy sector. <...> The United States and its allies have placed sanctions policies at the core of what they do on the international stage, including regarding Russia. This demonstrates their refusal to engage in fair economic competition and their commitment to using unfair, aggressive practices for suppressing their opponents.
***
#CollectiveWest
The West is intoxicated by its perceived “greatness,” its impunity, and its self-endowed authority to dictate the destinies of peoples worldwide. This reflects arrogance and a disdainful attitude towards the rest of the world. It is yet another brazen assertion that when we speak of “democracy,” it signifies merely one thing – “we do as we please.” <...> It is sheer hypocrisy, dictatorial behaviour, disrespect for the populace.
#UN
UN Security Council reform is needed. Not all countries that bear special responsibility in the global economy, finance, politics, and military affairs are represented in the UN Security Council. It has been pointed out repeatedly that countries such as India and Brazil have long earned permanent Security Council membership on all counts, as has Africa.
#RussiaChina
Russia-China partnership is among the key factors in stabilising the international arena and the ongoing processes that are used, among other things, to escalate confrontation and hostility in international affairs, which is what our neighbours from NATO engage in under US guidance.
#USA#Ukraine
As soon as Donald Trump assumes the presidency and articulates his final stance on Ukrainian matters, we will examine it. <...> The increasing reference to the realities “on the ground” is a development likely to be welcomed.
#RussiaSerbia
Our relations with Serbia are grounded solely in the interests of the Serbian and Russian peoples, as well as our respective states. Our interests align on the vast majority of issues. These relations are rich with specific agreements and projects, including those in the energy sector, approved by our heads of state, governments, and companies.
Read in full.
#Outcomes2024
#Outcomes2024
🎙 Russia's Foreign Minister Sergey Lavrov’s remarks and answers to media questions during a news conference on the outcomes of Russian diplomacy in 2024 (January 14, 2025)
💬 FM Sergey #Lavrov: We are living in a historical era of confrontation between those who uphold the fundamental principles of international law <...> which have been formulated, set out and put forth in the most important international document – the UN Charter – and those who are not satisfied with that document, who decided <...> that they could not live in accordance with the wishes of the “political West”, <...> those who oppose multipolarity.
President of Russia Vladimir Putin has repeatedly explained the true root causes of the special military operation in Ukraine. We had to begin to repel an attack, a war waged against us by the collective West with the main goal of suppressing competition when Russia re-emerged as its strong rival on the international arena.
Their main goal was to weaken our country geopolitically, creating direct military threats to us right on our borders, on Russia’s native territories, <...> in an attempt to slash our strategic potential and devalue it as much as possible.
The second reason also has to do with the history of the region, only it was more about the people who have lived on that land for centuries. <...> These people were labelled ‘terrorists’ by the current Ukrainian regime, which came to power through a coup d'etat. And when they refused to accept it, that regime launched an all-out offensive against all things Russian. <...>
There has been a revival in efforts to oppose the Western diktat, with emerging economies and new centres of financial power in China, India, ASEAN, the Arab world, and CELAC. This group also includes a resurgent Russia together with its allies from the EAEU, the CIS, and CSTO. This also includes the SCO and #BRICS.
The United States does not want to have any competitors anywhere, starting with the energy sector. <...> The United States and its allies have placed sanctions policies at the core of what they do on the international stage, including regarding Russia. This demonstrates their refusal to engage in fair economic competition and their commitment to using unfair, aggressive practices for suppressing their opponents.
***
#CollectiveWest
The West is intoxicated by its perceived “greatness,” its impunity, and its self-endowed authority to dictate the destinies of peoples worldwide. This reflects arrogance and a disdainful attitude towards the rest of the world. It is yet another brazen assertion that when we speak of “democracy,” it signifies merely one thing – “we do as we please.” <...> It is sheer hypocrisy, dictatorial behaviour, disrespect for the populace.
#UN
UN Security Council reform is needed. Not all countries that bear special responsibility in the global economy, finance, politics, and military affairs are represented in the UN Security Council. It has been pointed out repeatedly that countries such as India and Brazil have long earned permanent Security Council membership on all counts, as has Africa.
#RussiaChina
Russia-China partnership is among the key factors stabilising modern international life and the ongoing processes that are used, among other things, to escalate confrontation and hostility in international affairs, which is what our neighbours from NATO engage in under US guidance.
#USA#Ukraine
As soon as Donald Trump assumes the presidency and articulates his final stance on Ukrainian matters, we will examine it. <...> The increasing reference to the realities “on the ground” is a development likely to be welcomed.
#RussiaSerbia
Our relations with Serbia are grounded solely in the interests of the Serbian and Russian peoples, as well as our respective states. Our interests align on the vast majority of issues. These relations are rich with specific agreements and projects, including those in the energy sector, approved by our heads of state, governments, and companies.
#Outcomes2024
🎙 Russia's Foreign Minister Sergey Lavrov’s remarks and answers to media questions during a news conference on the outcomes of Russian diplomacy in 2024 (January 14, 2025)
Read in full
***
💬 FM Sergey #Lavrov: We are living in a historical era or confrontation between those who uphold the fundamental principles of international law <...> which have been formulated, set out and put forth in the most important international document – the UN Charter – and those who are not satisfied with that document, who decided <...> that they could not live in accordance with the wishes of the “political West”, <...> those who oppose multipolarity.
President of Russia Vladimir Putin has repeatedly explained the true root causes of the special military operation in Ukraine. We had to begin to repel an attack, a war waged against us by the collective West with the main goal of suppressing competition when Russia re-emerged as its strong rival on the international arena.
Their main goal was to weaken our country geopolitically, creating direct military threats to us right on our borders, on Russia’s native territories, <...> in an attempt to slash our strategic potential and devalue it as much as possible.
The second reason also has to do with the history of the region, only it was more about the people who have lived on that land for centuries. <...> These people were labelled ‘terrorists’ by the current Ukrainian regime, which came to power through a coup d'etat. And when they refused to accept it, that regime launched an all-out offensive against all things Russian. <...>
There has been a revival in efforts to oppose the Western diktat, with emerging economies and new centres of financial power in China, India, ASEAN, the Arab world, and CELAC. This group also includes a resurgent Russia together with its allies from the EAEU, the CIS, and CSTO. This also includes the SCO and #BRICS.
The United States does not want to have any competitors anywhere, starting with the energy sector. <...> The United States and its allies have placed sanctions policies at the core of what they do on the international stage, including regarding Russia. This demonstrates their refusal to engage in fair economic competition and their commitment to using unfair, aggressive practices for suppressing their opponents.
***
#CollectiveWest
The West is intoxicated by its perceived “greatness,” its impunity, and its self-endowed authority to dictate the destinies of peoples worldwide. This reflects arrogance and a disdainful attitude towards the rest of the world. It is yet another brazen assertion that when we speak of “democracy,” it signifies merely one thing – “we do as we please.” <...> It is sheer hypocrisy, dictatorial behaviour, disrespect for the populace.
#UN
UN Security Council reform is needed. Not all countries that bear special responsibility in the global economy, finance, politics, and military affairs are represented in the UN Security Council. It has been pointed out repeatedly that countries such as India and Brazil have long earned permanent Security Council membership on all counts, as has Africa.
#RussiaChina
Russia-China partnership is among the key factors stabilising modern international life and the ongoing processes that are used, among other things, to escalate confrontation and hostility in international affairs, which is what our neighbours from NATO engage in under US guidance.
#USA#Ukraine
As soon as Donald Trump assumes the presidency and articulates his final stance on Ukrainian matters, we will examine it. <...> The increasing reference to the realities “on the ground” is a development likely to be welcomed.
#RussiaSerbia
Our relations with Serbia are grounded solely in the interests of the Serbian and Russian peoples, as well as our respective states. Our interests align on the vast majority of issues. These relations are rich with specific agreements and projects, including those in the energy sector, approved by our heads of state, governments, and companies.