Что делать если нужно поставить какую-то 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
Several countries to import wheat from India after ban on shipment lifted
The agriculture ministry has projected a record 120 MT of wheat output in 2025-2026 crop years (July-June), trade sources said that output is definitely higher than 117 MT in 2024-25 crop year.
The area under wheat this season has increased to 33.41 million hectares (mha), 3% higher than last year, exceeding the normal sown area of 31.2 mha
#Agriculture
https://t.co/uvwNj9BuM7
Job Title: Poultry production manager
Job Type: On-site - Permanent (Full-time)
Job Sector:#Agriculture
Work Location: Gondar, Ethiopia
Experience Level: Senior
Vacancies: 1
Salary/Compensation: Monthly
Deadline: 8/11/2023
Description:
We are looking for a skilled poultry production manager who has at least a Bsc in animal science and related field. The applicant needs to have a minimum 6 years of experience. The location is Weleta.
__________________
Purpose Black Eth Trading s.c
[Verified Company ✅]
128 Jobs Posted
From: @freelance_ethio | @freelanceethbot
For our Amharic Channel, Join @afriworkamharic
🌎 The guano islands of Peru once fueled global agriculture. Thick layers of seabird droppings here created natural fertilizer so valuable, nations fought for control in the 19th century. ✨
#history⚡#ecology⚡#agriculture
👉subscribe Interesting Planet
#Koulouba | 06 mai 2025 | #Agriculture
15e Session du CSA : Priorité à la souveraineté alimentaire et au développement rural
Sous la présidence du Général Assimi GOÏTA, la 15e session du Conseil Supérieur de l’Agriculture (CSA)s’est tenue le 6 mai 2025 à Koulouba, réunissant le Premier ministre, des ministres clés et des représentants agricoles.
À l’ordre du jour :
- Bilan 2024 (inondations, insécurité)
- Exécution des recommandations précédentes
- Perspectives 2025-2027
🔷️Performances 2024 :
- 11M+ tonnes de céréales
- 640 000 tonnes de coton
- 97 000 tonnes de viande
- 113 000 tonnes de poisson
🔷️Mesures annoncées:
- Subventions :
- Coton (300 FCFA/kg)
- Engrais minéraux (14 000 FCFA/sac)
- Semences de maïs (1 500 FCFA/kg)
- Soutien à la mécanisation, pisciculture et crédit agricole
🔷️Objectif : Renforcer l’autosuffisance alimentaire et les chaînes de valeur locales.
🌎 Vertical farming—growing crops in stacked indoor layers—uses up to 95% less water than traditional agriculture, while reducing pesticide use and transportation emissions. Some modern vertical farms employ LED lighting and hydroponics, completely soil-free, to produce lettuce and herbs year-round in urban settings. ✨
#ecology⚡#technology⚡#agriculture
👉subscribe Interesting Planet
👉more Channels
🌎 The future of Earth’s ecology could be transformed by vertical farming—multistory indoor farms that use LED lighting and hydroponics to grow crops year-round. These farms use up to 95% less water than traditional agriculture and can be built in cities, reducing transport emissions and land use. ✨
#ecology⚡#technology⚡#agriculture
👉subscribe Interesting Planet
👉more Channels
🌎 The Amazon basin is home to “terra preta” soils—dark, fertile earth created by ancient humans mixing charcoal, bones, and compost. This enriched soil still boosts crop yields centuries later, showing early Amazon cultures mastered sustainable farming. ✨
#Amazon⚡#archaeology⚡#agriculture
👉subscribe Interesting Planet
News: #Ethiopia earns $288.48 million from horticulture exports in seven months, amid sector bottlenecks
Ethiopia has generated $288.48 million from the export of more than 160,000 tons of #horticultural products during the first seven months of the current Ethiopian fiscal year, the Ministry of #Agriculture announced, despite concerns raised by stakeholders over infrastructure gaps, logistics constraints, and land supply management.
The ministry disclosed the performance following a consultative meeting with relevant public institutions and local and foreign investors engaged in the horticulture sector to assess progress over the reporting period.
Minister of Agriculture Addisu noted that horticulture, alongside coffee, remains one of Ethiopia’s priority export commodities, highlighting its strategic importance in boosting foreign exchange earnings.
Ethiopia’s horticulture industry has faced mounting challenges in recent years, largely driven by security...
Read more: https://addisstandard.com/?p=55463
📹 VIDEO | Rice Producers Protest Agribusiness Pressure in Venezuela
Rice producers across Venezuela are taking to the streets ahead of the upcoming harvest, warning that prices offered by agroindustrial firms could leave many farmers unable to cover production costs.
Campesino groups say large conglomerates are using their control over silos, imports, and distribution to push prices down, while limited access to credit keeps farmers dependent on company financing.
After talks with producers, Agriculture Minister Julio León Heredia announced a provisional price. But campesino organizations warn they were barely represented in negotiations.
Click here to read our full report 👉🏾https://venezuelanalysis.com/news/venezuela-rice-producers-denounce-agribusiness-pressure-demand-govt-support-for-fair-prices/
#Agriculture#Peasants#Campesinos