Что делать если нужно поставить какую-то 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
🖊OPINION | The Kidnapping of Venezuela’s Sovereignty
"The kidnapping of Nicolás Maduro and National Assembly deputy Cilia Flores should compel a fundamental reassessment of the state of the international order."
Tricontinental Institute researchers Atul Chandra and Tings Chak look at the recent US attacks and their implications for multilateralism and international law.
Follow the link to read the article: https://venezuelanalysis.com/analysis/the-kidnapping-of-venezuelas-sovereignty/
#InternationalLaw#Multilateralism#Sovereignty#NicolasMaduro
🌐Today is International Day of Multilateralism and Diplomacy for Peace.
On December 12, 2018, the UN General Assembly passed a resolution A/RES/73/127 on marking this day. The document notes that the International Day aims to promote UN values and to reaffirm the trust of the world’s nations in the goals and principles of the UN Charter.
🇷🇺🇺🇳 Russia is invariably committed to the policy of upholding multilateralism and the UN’s leading role in global affairs and is actively involved in efforts to overhaul the UN and to adapt it to new international realities.
This is particularly topical today when a narrow group of states advancing the rules-based order concept exerts unprecedented pressure on the UN and other multilateral institutions.
✍️ Under the Russian Foreign Policy Concept, approved on March 31, 2023, Russia intends to prioritise efforts to reinstate the UN’s role as a central coordination mechanism in coordinating the interests of UN member states.
At the same time, one of the main aims of national foreign policy is to strengthen the potential of multilateral regional associations and integration organisations involving Russia. For example, this refers to measures to enhance the international role of #BRICS, the #SCO, the #CIS, the #EAEU, the #CSTO, #RIC and other interstate associations and international organisations, as well as mechanisms with significant Russian involvement.
⏰ Today, on April 24, FM Sergey Lavrov will take part in one of the key events of Russia’s presidency of the UN Security Council, specifically, the open debate on "Effective multilateralism through the defence of the principles of the Charter of the United Nations." The debate will be streamed live on all our feeds.
#UNCharterIsOurRules#Multilateralism
La Convenzione di Hanoi: un nuovo pilastro globale contro il crimine cibernetico
Il 25 ottobre a Hà Nội è stata firmata la Convenzione ONU contro il crimine cibernetico, primo strumento universale che unisce sicurezza digitale, cooperazione giudiziaria e tutela dei diritti umani in un’unica cornice globale.
Con quasi 70 Paesi firmatari già nella giornata inaugurale, il trattato segna una svolta nella governance del cyberspazio e un importante riconoscimento del ruolo crescente del Việt Nam come attore diplomatico di primo piano.
La “Convenzione di Hanoi” mira a:
Armonizzare le definizioni di reati informatici e le procedure investigative.
Favorire lo scambio di prove elettroniche e la cooperazione giudiziaria.
Proteggere i diritti fondamentali e promuovere la fiducia tra Stati.
Rafforzare la sicurezza digitale globale senza sacrificare la libertà online.
Per il Việt Nam, ospitare la firma è molto più che un gesto simbolico: è la conferma di una leadership multilaterale proattiva e della volontà di contribuire alla costruzione di un cyberspazio sicuro, equo e aperto.
Come ha ricordato António Guterres, “la vera forza della Convenzione sarà trasformare le firme in azione concreta”.
Se il mondo saprà cogliere questa opportunità, Hà Nội 2025 resterà nella storia come il giorno in cui la comunità internazionale ha iniziato davvero a mettere legge nel cyberspazio.
#HanoiConvention#Cybercrime#UN#Vietnam#DigitalDiplomacy#CyberSecurity#Multilateralism
https://www.marx21.it/internazionale/la-convenzione-di-hanoi-come-nuovo-pilastro-globale-contro-il-crimine-cibernetico/
@RusEmbMalta:
🇷🇺🛡️13th International Security Meeting to Be Held in Moscow
📅 On May 27–29, 2025, Moscow will host the 13th International Meeting of High Representatives for Security Issues under the chairmanship of Secretary of the Russian Security Council Sergey Shoigu.
🌍 More than 150 countries from the Global South and East have been invited to participate, along with representatives of the #CIS, #CSTO, #EAEU, #SCO, and over 20 international organizations.
🗂️ The meeting will focus on strengthening international security cooperation. Discussions will cover a broad range of challenges, including terrorism, extremism, transnational crime, drug trafficking, and emerging threats.
🧭 Since 2010, this annual platform has brought together senior security officials to build trust, share expertise, and coordinate efforts on pressing global security issues.
📌 Media accreditation is open until May 20, 2025.
#Shoigu#SecurityCouncil#InternationalMeeting#Moscow2025#GlobalSecurity#Counterterrorism#Multilateralism#CIS#SCO#BRICS#CSTO#EAEU#GlobalSouth