Что делать если нужно поставить какую-то 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
🚨Переломный момент 🚨
Сегодня – Международный день чистой энергии. Знали ли вы, что
Великобритания достигла более 50% возобновляемой электроэнергии в течение
ЧЕТЫРЕХ кварталов подряд!
Еще впечатляющее: 58% электроэнергии Британии
поступило из чистых источников в 2024 году, а последняя угольная электростанция
навсегда закрылась в сентябре.
🌎Будущее – за возобновляемой энергией! 🌎
#CleanEnergy#SustainableFuture
Everyone deserves the right to nutritious, affordable, and sustainable food.
On #WorldFoodDay, let's commit to working towards a world where everyone has access to the food they need for a healthy and fulfilling life.
#HealthyLiving
#FoodSecurity#SustainableFuture
January 28 — International Reducing CO₂ Emissions Day
📸👩🏫👨🏫Every action counts! Today is a reminder that students are not just learners, but future leaders of a more sustainable world.
✔️From saving energy and choosing public transport to supporting green innovations, small daily choices can make a big difference for our planet.
🔼Let’s work together for cleaner air, a healthier environment, and a greener future. The change starts with us.
#GreenUniversity#ClimateAction#CO2Reduction#SustainableFuture
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
🌟 Celebrating 80 Years of the Russian Nuclear Industry! 🌟
Today marks a historic milestone — the 80th anniversary of the Russian nuclear industry.
It’s not just a story of technology and science, but of vision, resilience, and the determination to transform challenges into opportunities for the future.
⚛️ Breakthroughs that redefined possibility
The Russian nuclear industry became a leader in the peaceful use of atomic energy. The world's first nuclear power plant in Obninsk was launched, created the first nuclear icebreaker and tokamak.
🚀 Rosatom today
Today, the State Corporation "Rosatom" creates advanced technologies for a wide range of industries: today the state corporation not only builds nuclear power plants, providing clean energy to the country and the world, but also creates new materials — super-strong, environmentally friendly, helps develop the Arctic and the Northern Sea Route, develops
nuclear medicine methods to defeat incurable diseases, advances quantum technologies to solve global human problems.
👨👩👧👦 A dream for the future
Today, the nuclear industry has a big new dream — a long and healthy life for people through clean atomic energy, advanced nuclear medicine methods, new materials, and modern digital technologies.
🌍 We dream of a world where energy is limitless, life is healthier, and humanity thrives. And together, we will make this dream a reality.
We are proud & happy! ✨
#NuclearEnergy#CleanPower#Innovation#SustainableFuture
Green University Students Join Tashkent “Young Ecologists” Council
🎓Council members:
🟢Deputy Chair: Baxtiyorova Saodatxon
🟢Manager of Ecological Innovation, Startups and Grants: Danayeva Farzona-bonu
🦉This membership gives our students the opportunity to actively participate in ecological initiatives, innovations and the development of a green economy.
#YoungEcologists#GreenUniversity#Ecology#Innovation#SustainableFuture
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
🏔️International Mountain Day
🗓Today, we celebrate International Mountain Day — a reminder of the incredible role mountains play in our lives. They provide fresh water, protect unique ecosystems, and inspire millions around the world.
🌱Let’s raise awareness, appreciate nature, and work together to preserve these powerful landscapes for future generations.
#InternationalMountainDay#SustainableFuture#GreenUniversity#YouthForNature#EcoAwareness
✉️[email protected]
☎️ +998 55 512 00 77
📍Location
🌐Website | 📱Telegram | 📱Instagram | 📱LinkedIn | 🟥YouTube
📣 Eco Club JMCU — tabiat uchun birlashgan yangi oila! Har bir uchrashuv — yashil kelajak sari qo‘yilgan bir qadam.🌿
💬💬💬
📣 Eco Club JMCU — a new family united for nature! Each meeting is a step toward a greener future.🌿
💬💬💬
📣 Eco Club JMCU — новая семья, объединённая ради природы! Каждая встреча — шаг к зелёному будущему.🌿
#EcoClubJMCU#GreenFamily#SustainableFuture#GoGreen#EcoLife#NatureMatters
🕊Telegram |📱Instagram
☀️ “Ziyo Forum” yoshlar markazida BMT kuni munosabati bilan “Youth United for the UN Day: Empowering Sustainable Future” sessiyasi bo‘lib o‘tdi!
🇺🇳27-oktabr kuni “Ziyo Forum” yoshlar markazida yoshlar uchun ilhomlantiruvchi sessiya tashkil etildi. Tadbir davomida Alisher Asrorov— UNODC Youth Network Leader in Uzbekistan, Webster Universitetining Career & Business Development menejeri va sobiq BMT Yoshlar Kengashi raisi — BMTning O‘zbekistondagi faoliyati, Barqaror Rivojlanish Maqsadlari (SDGs) hamda yoshlarning global tashabbuslardagi o‘rni haqida o‘z tajribasi asosida so‘zlab berdi.
📌Ishtirokchilar ochiq muloqotda faol qatnashib, “Kahoot” viktorinasida o‘z bilimlarini sinovdan o‘tkazishdi. Tadbir yakunida eng faol yoshlarga maxsus sovg‘alar topshirildi va umumiy suratga tushildi.
🌍Sessiya iliq va ilhomlantiruvchi muhitda o‘tib, yoshlarni global fikrlash va barqaror kelajak sari ilhomlantirdi.
📸 Barcha suratlarni quyidagi havola orqali ko‘rishingiz mumkin:
👉https://disk.yandex.ru/d/1A8GU1Uc6bujhg
☀️ “Youth United for the UN Day: Empowering Sustainable Future” session was successfully held at Ziyo Forum Youth Center!
🇺🇳On October 27, a special and inspiring session took place at the Ziyo Forum Youth Center. Alisher Asrorov— UNODC Youth Network Leader in Uzbekistan, Career & Business Development Manager at Webster University, and former Chair of the UN Youth Advisory Board — shared his insights on the UN’s role in Uzbekistan, the Sustainable Development Goals (SDGs), and the importance of youth participation in global initiatives.
📌Participants actively engaged in open discussions and tested their knowledge through the interactive Kahoot quiz. The most active attendees received special gifts, and the event concluded with a group photo.
🌍The session took place in a warm and inspiring atmosphere, motivating young people to think globally and contribute to a sustainable future.
📸 Check out all the event photos at the link below:
👉https://disk.yandex.ru/d/1A8GU1Uc6bujhg
#ZiyoForum#UNDay#YouthEmpowerment#SustainableFuture#UNUzbekistan#SDGs#YouthCenter
#ClimateCrisis
🌍 The world is sinking into fossil fuels
Oil, gas, and coal account for 75% of global greenhouse gas emissions and nearly 90% of CO₂ emissions.
🔥 2024 became the hottest year in recorded history — global temperatures have risen 1.5°C above pre-industrial levels for the first time (according to @CopernicusClimate).
❄️ Consequences:
• Melting of polar ice caps
• Rising sea levels
• Intensifying storms and droughts
• Populations who contributed least to climate change are suffering the most
⛽️ Despite the crisis, consumption of oil, gas, and coal is increasing.
🌡 According to @UNEP, 2024 set a record for CO₂ emissions.
Many governments and corporations are promising “net zero,” yet in practice, fossil fuel extraction is being doubled.
🗣 “Governments are doubling fossil fuel extraction — this is double the risk for humanity and the planet,”
— said UN Secretary-General António Guterres.
📊 According to the @InfluenceMap report:
Just 57 corporations and state-owned companies were responsible for 80% of CO₂ emissions from fossil fuel and cement production between 2016 and 2022.
💡 The solution is a transition to clean energy and local resources.
But without transparency, investigative journalism, and public pressure, change will not happen.
🟢 Climate responsibility is not an abstract concept. It involves real names and real actions.
#EcoUz#ClimateCrisis#Copernicus#UNEP#CleanEnergy#ZeroEmission#StopFossilFuel#AralRegion#SustainableFuture
☘️Read the latest environmental news on the @ekologuz page. Follow us and send your suggestions and wishes via @eklguz_bot
Instagram | Facebook | Twitter | Sayt | Youtube.