Что делать если нужно поставить какую-то 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
Live: Dazzling nightscape at Shanghai's Yangpu Riverside
As APEC's host again after a 12-year interval, China is holding the Second Senior Officials' Meeting and related #APEC meetings in Shanghai. As night falls, the Yangpu Riverside in Shanghai comes alive with dazzling lights. The shimmering river reflects rows of towering skyscrapers, blending waterfront tranquility with the bustling glamour of a global metropolis. Bright neon lights glimmer along the bank, and gentle river breezes brush past the promenade, painting a picture of Shanghai's modern prosperity and timeless elegance.
via CGTN
#APEC 2024 : les point clés de la dernière journée du sommet
Le sommet de l'APEC s’achève par une ultime réunion dans la capitale du #Pérou. Une déclaration finale doit être adoptée à l'issue du sommet. Les détails avec notre envoyé spécial sur place, Igor Kourachenko.
RT en français • Osez questionner !
#APEC 2024 : les points clés de la deuxième journée du sommet
La deuxième journée du sommet de l’APEC a commencé au #Pérou. Plus de détails avec notre envoyé spécial Igor Kourachenko, qui est sur place.
RT en français • Osez questionner !
🌐APEC Ministers Commit to Trusted AI and Inclusive Digital Growth
APEC digital and AI ministers convened for the first time in Incheon, Republic of Korea, issuing a joint statement that redefines regional priorities for AI governance. The meeting underscored a united commitment to responsible digital transformation and the development of trusted AI systems aligned with economic and societal needs.
The ministers identified three focal points: accelerating AI innovation to solve socio-economic challenges, expanding equitable digital connectivity, and building a secure, transparent AI ecosystem. Korea’s initiative to launch a dedicated APEC AI program by the end of 2025 was met with strong support, positioning the region to lead on practical, multilateral AI governance.
#AIandLaw#APEC#AIRegulation#AsiaPacificAI
🎙 Foreign Minister Sergey Lavrov’s video address to the 9th international conference "Russia and China: Cooperation in a New Era" (May 30, 2024)
💬 I am delighted to welcome the organisers of and participants in the 9th international conference "Russia and China: Cooperation in a New Era".
Most recently, Russia's President Vladimir Putin paid a state visit to China, which definitely became the centerpiece of bilateral exchanges this year. <...>
🇷🇺🇨🇳 The bond of comprehensive partnership and strategic cooperation between Russia and China has grown unprecedentedly strong thanks to the personal efforts of both heads of state. The Beijing summit sealed the two countries’ firm commitment to further deepen and expand it. This commitment was documented in the two leaders’ joint final statement.
This year, Russia and China celebrate 75 years of diplomatic relations. We mark this significant anniversary with achieving a new quality of relations – today, Russia and China view each other as priority partners and invariably adhere to the principles of mutually respectful, equal and trustful cooperation. We support each other with regard to key issues affecting the respective fundamental interests.
<...>
Strategic coordination in the international arena remains a key component of the Russian-Chinese partnership amid the growing international tensions. Our foreign policy tandem, held together by a broad commonality of interests as well as coinciding or similar approaches to key issues on the present-day agenda, plays a major stabilising role in global affairs.
☝️ The two countries are strengthening cooperation on multilateral platforms, primarily the Unite Nations and the UN Security Council, as well as #BRICS, #SCO, #G20, and #APEC.
<...>
The Russian-Chinese strategic tandem is gaining status, and this opens up new horizons for us in terms of stronger sovereignty, economic growth, and prosperity of both countries.
Read in full