Что делать если нужно поставить какую-то 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
Demotaktiken für Fortgeschrittene:
Weissrussen durchbrechen eine Polizeikette, kesseln diese ein und drängen sie zurück. #Belarus
𝙎𝙘𝙝𝙬𝙖𝙧𝙢𝙗𝙚𝙬𝙪𝙨𝙨𝙩𝙨𝙚𝙞𝙣
Wenn wir allgemein mehr als Kollektiv 🕸🌐 agieren würden anstatt im Ego 🎭🦧, dann können wir gemeinsam die Welt ins positive verändern 🌱, wenn wir alle zusammenhalten 🤝 und uns nicht spalten lassen, von oben. ☝️
The future of the Union State is in the hands of the young!
📍On September 24, 2024, the solemn closing ceremony of the republican youth project "Road Train #Belarus" took place at the Brest Fortress memorial complex.
🔛Over the course of 8 days, young people from different parts of Belarus and Russia visited regions of the Republic of Belarus: they got acquainted with the culture and traditions of settlements, visited large and city-forming enterprises, where they were able to exchange experiences, they also took part in charity, sightseeing, educational, sports and socially useful events.
🔛This year, the number of participants from Belarus and Russia has reached 120!
🔛The project proved the importance of interaction between student, scientific, creative and working youth of the Union State.
The youth project has been implemented by the Republican Youth Center since 2022, with the support of the Ministry of Education of Belarus.
💚Follow Rosmolodezh. +World
[eng]
The republican project "Auto-train #Belarus.Youth.Pro" started in Minsk
The republican project "Auto-train #Belarus.Youth.Pro" will unite 120 young men and women - representatives of student, scientific, creative and working youth from Belarus and Russia on 17-24 September.
"We congratulate you on the grand opening of this project. These days will be filled with unforgettable communication and new projects. It is not by chance that the start is given exactly on 17 September, on the Day of National Unity. Let us unite our efforts for the sake of a better future of our countries [Belarus and Russia - note: youth.bel]. Young people, the word is yours. Happy holiday! Happy National Unity Day!", said Deputy Minister of Education Katerina Petrutskaya during the opening ceremony of the project.
The youth project has been implemented by the Republican Youth Centre since 2022, with the support of the Ministry of Education of Belarus.
@Moladz_by
🎉On 2 April Russia and Belarus celebrate the Day of Unity of the Peoples🇧🇾🇷🇺
📝On 2 April 1996 a treaty on the establishment of the Community of Russia and Belarus was signed, which allowed to create conditions for consistent mutual integration of the two countries in foreign policy, trade and economic, interregional, scientific and technical, cultural, humanitarian and other spheres
📌 Another crucial area of cooperation between Russia and Belarus is the sphere of youth policy
Today, Rosmolodezh together with the Ministry of Science and Higher Education of the Russian Federation, the Ministry of Education of the Russian Federation and other relevant agencies are working on one of the key tasks in this area, namely harmonisation of russian and belarusian approaches to youth policy ✅
Thus, 2023 was filled with collaborative youth events, activities and trips. For example,
✔️The all-Russia Youth Forum "SHUM" in Kaliningrad brought together media professionals from Russia and Belarus
✔️The Forum of the Youth of Russia and Belarus in Bashkortostan welcomed 500 young Russian and Belarusian leaders
✔️Russian young people took part in the International Youth Forum "Friendship without Borders" in Minsk region
✔️Young people travelled through all regions of Belarus on the bus #Belarus.Youth.Creation.
And this is only a small part of our joint work!
We congratulate our colleagues, in particular the Ministry of Education of the Republic of Belarus, the Belarusian Republican Youth Union, the Republican Youth Centre, and thank them for our joint work and wish us new common achievements! 🥳
🇧🇾🇷🇺Auto-train across Belarus!
From 15th to 21st September more than 80 young men and women, representatives of student, scientific, creative and working youth from the Republic of Belarus and the Russian Federation, took part in the republican project "Auto-train #Belarus.Youth.Creation".
The participants travelled around a number of settlements of Belarus, where charitable, excursion, educational, sports, cultural and socially useful events were held.
The road train finished in Minsk on 21st September, the International Day of Peace.
The patriotic project "Auto-train #Belarus.Youth.Creation" became a huge contribution to the volunteer movement of the Union State and gave the guys an opportunity to learn a lot of new things and make friends❤️
🇨🇳🇧🇾 Belarus lauded by Xi as China's true friend
Chinese President Xi Jinping praised Belarus as a true friend of China as he met Alexander Lukashenko, the leader of the nation, on Wednesday and urged the Russian ally to join Beijing in opposing "hegemony and bullying".
Xi, greeting Lukashenko in Zhongnanhai, the seat of power in Beijing, congratulated him on his re-election, Xinhua reported, adding that China and Belarus were "true friends and good partners."
"You have very accurately pointed out the main feature of our time - the unprecedented pressure from the West on us, primarily on the People's Republic of China," Belarus' state news agency BelTA cited Lukashenko as saying.
#China#Belarus
@asianomics
🗣Pressesprecherin des russischen Außenministeriums Maria Sacharowa zum Jahrestag des Vertrags zwischen Russland und Belarus über die Schaffung eines Unionsstaates
💬 Am 8. Dezember 2025 jährt sich der Vertrag über die Schaffung eines Unionsstaates zum 26. Mal. Für Russland und Belarus markierte dieses Ereignis eine neue Etappe im Prozess der Völkervereinigung auf Grundlagen der souveränen Gleichheit, der freiwilligen und gewissenhaften Umsetzung der gegenseitigen Verpflichtungen.
💬 Im Laufe vieler Jahre der Integrationsprozesse in ganz unterschiedlichen Bereichen hat sich der Unionsstaat zu einem der fortschrittlichsten und ambitioniertesten Integrationsprojekte in Eurasien entwickelt.
💬 Es wurden erhebliche Fortschritte bei der Bildung eines gemeinsamen sozial-ökonomischen, verkehrslogistischen, kulturellen und humanitären Raums sowie Migrations- und Informationsraums erzielt. Zugleich wird die finanzwirtschaftliche und wissenschaftlich-technologische Souveränität des Unionsstaates kontinuierlich gestärkt.
💬 Die Stärkung des Verteidigungs- und Sicherheitsraums im Unionsstaat ist zu einer Forderung der Zeit geworden. Es wurde ein solides Fundament für gegenseitige Verpflichtungen im Rahmen des Bündnisses in den Bereichen Verteidigung, Schutz der Souveränität, der Unabhängigkeit und der verfassungsmäßigen Ordnung Russlands und Belarus geschaffen. Ebenso werden alle verfügbaren Kräfte und Mittel dafür eingesetzt, dass die Integrität und die Unantastbarkeit des Gebiets des Unionsstaats und seiner Außengrenze gewährleistet werden.
💬 Bei der schrittweisen Erweiterung des gemeinsamen kulturellen und humanitären Raums werden die Bewahrung des historischen Gedächtnisses und die patriotische Erziehung der Jugend in den Mittelpunkt gerückt. Dieses Jahr begeht man in Moskau und in Minsk feierlich den 80. Jahrestag des Sieges im Großen Vaterländischen Krieg.
💬 Wir haben zwar bereits einen beträchtlichen Weg zurückgelegt, aber wir haben nicht vor, stehenzubleiben. Wir werden weiterhin den Willen unserer brüderlichen Völker zur Einheit, zur Ausweitung einer breit angelegten Zusammenarbeit und zur Vertiefung der strategischen Partnerschaft in allen Bereichen verwirklichen. All dies dient den Interessen des sozioökonomischen Fortschritts beider Staaten, der Stärkung ihrer Positionen auf der internationalen Bühne und der Verbesserung des Wohlstands unserer Bürger.
🔗Quelle
@RusBotschaft
#Russland#Belarus