Что делать если нужно поставить какую-то 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
"We are living in unprecedented times, but with fortitude and resilience, we can and will stand in solidarity as one united Singapore – to beat this crisis and emerge stronger as a nation." -- DPM Heng Swee Keat
#SGTogether#SGUnited
Catch Mr Liang Eng Hwa’s LIVE interview on Capital 95.8FM Tonight, 6.30pm!
Join us in discussing the Budget, Digitalisation & Jobs and national issues! Also find out what our citizens have to say through feedback collected by REACH. Stay tuned!
#SGUnited#SGTogether
More: https://www.facebook.com/92744267226/posts/10157332345052227
As we approach the end of the Circuit Breaker, measures will be progressively lifted in three phases from 2 June. Many restrictions in place will continue in Phase 1.
#SGUnited#SGTogether.
The Government announced that there will be gradual easing of Circuit Breaker measures. What are the services that will resume operation? Find out here!
#SGUnited#SGTogether
In our compact city, planning for the many different land use needs is often like a balancing act. By working together, we can make future Singapore a space for our hopes and dreams.
We've just launched Phase 2 of the Long-Term Plan Review public engagement exercise - come share your ideas at: go.gov.sg/ltpr
#LTPR2021#SGTogether
💡What do you value more in shaping a liveable Singapore: a good transportation network, convenient access to amenities, greenery in the city or the other factors above?
We're calling for your views and ideas in our online poll for the Long-Term Plan Review. With your participation, we can develop long-term land use plans that will better meet your needs and aspirations as well as those of future generations!
Tell us more at: go.gov.sg/ltpr
#LTPR2021#SGTogether
📣 We just launched our public engagement for the Long-Term Plan Review (LTPR) today and are excited to develop plans for Singapore's next chapter with you over the next year!
The #LTPR2021 is the latest review of plans that will steward land resources not just for today's use but also for future generations over the next 50 years and beyond.
We'd love to hear your hopes and aspirations for the future to develop these long-term plans! Watch how long-term planning has shaped the everyday lives of fellow citizens as well as what they dream for our future city - and share your dreams with us in our online poll at go.gov.sg/ltpr
#SGTogether
Where there are wet and dark crevices, NEA’s Dengue Inspection Officer Marthandan will be there. Let him show you how he and his team spot and tackle mosquito breeding in the areas around you!
Join him in our #NEAOfficers Story Highlight on our Instagram profile (www.instagram.com/nea_sg)!
#SGUnited#SGTogether
It has been more than a year since COVID-19 happened. Many of us have had to adapt to new work situations and overcome the various challenges the pandemic brought with it.
Today, we salute all workers, especially the frontliners who have been working extra hard to keep us safe this past year.
Happy Labour Day! 💪🇸🇬
#SGUnited#SGTogether
This National Day, let us celebrate the Singapore spirit that has kept us going during the most challenging of times. It will continue to help us emerge stronger for the future.
Happy 56th Birthday, Singapore!
#TogetherOurSGSpirit#SGUnited#SGTogether