Что делать если нужно поставить какую-то 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
#COS2025 – We will continue to support the healthcare sector by increasing our healthcare facilities islandwide and strengthening the healthcare workforce. Read more ⬆️
Infographic: Ministry of Health
#COS2025 – The Government will continue to support the health and well-being of people across all ages. Some of our plans include:
✅Grow Well SG, a programme with scheduled health checks and screenings for students
✅Continued support of active ageing initiatives and senior volunteerism
✅Improving accessibility to mental health services
Find out more above ⬆️
Infographic: Ministry of Health
#COS2025 – The Government is committed to nurturing a culture of giving and co-creation. We will do this through:
✅ Added funding for our social services
✅ Supporting community-centric, ground-up initiatives
✅ A 10-year Transformation Roadmap for co-ops
✅ Increasing engagements with our youth in building a shared future
Infographic: Ministry of Culture, Community and Youth
#COS2025 – We will provide various platforms to support the sporting and artistic aspirations of the people through:
1️⃣ Increasing support for Arts education across all ages, with new scholarships and programmes
2️⃣ The Sports Facilities Master Plan to make sports facilities affordable for the public
3️⃣ Improving support for persons with disabilities with 5 Para Sports Community Hubs and a Sports Fund
4️⃣ A Frailty Prevention Programme to promote healthy lifestyles for seniors
5️⃣ Improving the support system for our local athletes
Infographic: Ministry of Culture, Community and Youth
#COS2025 – The arts and heritage play a vital role in strengthening our national identity. The Government will continue to support this sector by:
✅Encouraging Singaporeans to attend local arts and heritage programmes
✅Promoting participation in arts programmes to enliven our public spaces
✅Safeguarding our heritage through Heritage Activation Nodes and supporting our heritage businesses
Infographic: Ministry of Culture, Community and Youth
#COS2025 – The Government will continue to strengthen social cohesion and bring people together to create an inclusive community for the future.
Find out more about our initiatives and plans. ⬆️
Infographic: Ministry of Culture, Community and Youth
#COS2025 – Building a brighter and better Singapore for all families calls for whole-of-society support. This includes:
➡️ Providing enhanced assistance and resources to parents
➡️ Empowering vulnerable groups, including persons with disabilities and their families
➡️ Strengthening partnerships across sectors for a strong social service ecosystem
Infographic: Ministry of Social and Family Development
#COS2025 – We will keep healthcare affordable and sustainable for all by:
✅ Improving healthcare affordability for outpatient treatments
✅ Strengthening support for oral health
✅ Improving support and affordability of long-term care
✅ Having better support for fertility preservation
✅ Having more drugs eligible for enhanced subsidies
Find out more ⬆
Infographic: Ministry of Health
#COS2025 – The Government is committed to supporting Singaporeans and businesses to become future-ready. We will continue to:
1⃣ Empower Singaporeans to build resilient careers through Career Health SG
2⃣ Transform businesses with a new Enterprise Workforce Transformation Package to adapt and grow
3⃣ Foster inclusive and safe workplaces through the review of the Employment Act
Infographic: Ministry of Manpower
#COS2025 – Here’re the key initiatives and updates to drive Singapore’s green transition forward.
Find out more here.
Infographic: Ministry of Sustainability and the Environment
#COS2025 – We will maximise the potential of education by:
✅Nurturing students holistically and fulfilling their potential
✅Supporting students with special educational needs
✅ Supporting lifelong learning
Find out more here.
Infographic: Ministry of Education