Что делать если нужно поставить какую-то 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
Sheep can feel emotions like fear, anger, boredom, and happiness. They evaluate their surroundings using checks like suddenness, familiarity, predictability, and control, similar to humans. Sudden events can cause fear, while predictable environments may lead to boredom.
🐑⚽️
@googlefactss
#AnimalWelfare#Sheep#Emotions#AnimalCare#Nature
🇳🇴 NORWAY PHASES OUT UNNATURALLY FAST-GROWING “FRANKEN-CHICKENS”
Norway has announced a gradual phase-out of so-called “franken-chickens” by 2027.
Norway, where about 70 million chickens are raised annually for food production, has become the first country to commit to raising 100% of its poultry under conditions that ensure high animal welfare standards. Animal rights advocates have welcomed the decision, calling it a “historic moment.”
“Franken-chickens,” often referred to in Norway as “turbo-chickens,” are fast-growing birds bred through selective breeding to reach maximum weight in the shortest possible time. Due to rapid growth and extreme size, these chickens suffer from numerous health problems, and most animal welfare organizations strongly condemn this practice.
According to Humane World for Animals, franken-chickens reach their “slaughter weight” in just six weeks, leading to severe strain on their bones, muscles, and ligaments. Their bodies often begin to break down as they grow, and many birds lose the ability to move. Humane League UK describes their lives as “extremely short and painful.”
The animal protection coalition Anima International has been campaigning for five years to eliminate fast-growing chicken breeds in Norway. Several animal welfare groups are also calling for similar measures in the United Kingdom.
Experts emphasize that this decision marks a significant step forward in improving animal welfare.
#AnimalRights#Norway#AnimalWelfare#PoultryFarming#ProtectAnimals
☘️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
#ForBritain policy: Fully investigate #BadgerCulling with the aim of bringing it to an end.
#AnimalWelfare#BadgerCull#BanBadgerCulling
Full manifesto here: https://www.forbritain.uk/manifesto/
🐾 WEBINAR ALERT: Rabies Elimination and Animal Welfare 🐾
Join us for a focused, hard-hitting session featuring leading voices in veterinary medicine, public health, and youth advocacy. Our expert panel will break down the most pressing issues, from emergency shelter response to global rabies elimination strategies.
📅Date: Feb 19
⏰Time: 2:30 L.T
📍Platform: t.me/aau_ohc
🎤MEET THE PANELISTS:
🔹 Dr. Mesfin Semu Wodajo
Graduate of Moscow Veterinary Academy (1994) and Utrecht University (2000). Former Associate Researcher at Tetracore, LLC. 14 years as Chief of Staff at Banfield Pet Hospital. Currently Medical Director & Owner at Upper Marlboro Veterinary Hospital.
🔹 Dr. Alazar Ayele
Veterinarian specializing in mobile pet care. Co-founder of Beyond Student for Change initiative. Operates a mobile veterinary clinic to expand access to professional animal healthcare and leads community-based stray dog mass rabies vaccination campaigns.
🔹 Dr. Biruk Eshetu
University of Gondar graduate (2015 E.C.). Former founder & president of One Health Innovation Club and VP of Clinical Medicine Club at UoG. Currently Manager of the Animal Welfare and Protection Trauma Shelter, Addis Ababa, where he works extensively with pets and shelter animals.
🔹 Yared Ermiyas
DVM Candidate, Co-founder of AAU One Health Club, and Animal Welfare Advocate.
🎙️Format:Live
📲 Set a reminder and join us!
👇 Drop a "👋" in the comments if you'll be there!
#RabiesElimination#AnimalWelfare#OneHealth#YouthAdvocacy#Webinar#VeterinaryMedicine#ShelterAndRescue
#DairyIndustry#AnimalWelfare#Cattle#AnimalWelfarePolicy#Reformthedairyindustry#UKDairy#Milk#Dairy#ForBritain
Our FULL manifesto can be found here: https://www.forbritain.uk/manifesto/
The UK government has unveiled an unprecedented plan to gradually eliminate animal testing in medical and pharmaceutical research.
The first phase will begin at the end of 2026 and will eliminate tests on mice used to develop treatments for skin and eye irritations.
Additionally, the country has committed to reducing the use of dogs and primates in laboratories by 35% by 2030, fulfilling an election promise made by the Labour Party.
Backed by £60 million, the strategy aims to promote ethical and technologically advanced alternatives that replace animal models without compromising the safety of vaccines, medicines, or pesticides.
Although animal experiments peaked in 2015 — with over 4 million animals used — advances in alternative methods had already helped reduce that number.
However, progress has stalled in recent years, so this new initiative seeks to accelerate the full replacement of animals.
Science Secretary Patrick Vallance stated, “Nobody wants to witness animal suffering,” and the new roadmap will allow governments, companies, scientists, and animal welfare organizations to collaborate on faster and more effective solutions.
Part of the investment will go to a specialized center that will integrate technology, data, and expertise to accelerate the transition to animal-free science.
🐾 Do you think Uzbekistan should implement a similar plan to reduce and replace animal testing? 🇺🇿💭
#AnimalWelfare#AnimalFreeScience#UK#AnimalTesting#ScientificInnovation#LabAnimals#ADNMascotas#AnimalNews#AnimalProtection#OneHealth☘️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.
Vitalik Buterin Donates to Thai Zoo
Ethereum co-founder Vitalik Buterin donates 10 million Thai baht (~$292,230) to Khao Kheow Zoo, Thailand. The donation, in two installments, starts December 26, 2024. Buterin and family will be adopted by the zoo. Details: Khao Kheow Zoo Announcement
#VitalikButerin#Ethereum#KhaoKheowZoo#Donation#Crypto#Blockchain#Thailand#AnimalWelfare#Charity#Adoption#Philanthropy#Zoo#MOODENG#CommunitySupport#TechForGood#EthereumCoFounder#News