Что делать если нужно поставить какую-то 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
When paying respects this Qing Ming, let’s continue to be socially responsible and observe #SafeDistancing measures. As crowds are expected at Choa Chu Kang Cemetery and government-managed columbaria, visitors are advised to send 2 representatives per household (with not more than 8 pax per group). The opening hours will be extended to 24-hours, with effect from 20 Mar until 18 Apr 2021.
Visitors driving to Mandai Columbarium during peak days will also be required to book an appointment. Visit www.nea.gov.sg/qingming2021 for more information.
From 12 Sep 2020, weekend visitors to the 4 popular markets (Geylang Serai Market, Chong Pang Market, Block 20/21 Marsiling Lane, and Block 505 Jurong West Street 52) will not be subject to the odd/even date entry restriction. However, the caps on the number of patrons allowed in the market at any one time will still be in place, to ensure sufficient #SafeDistancing. More information available at https://go.gov.sg/nea-lifting-entry-restriction-markets-12sep
During Phase 2, you may leave your home to smoke, but do so in an area where smoking is not prohibited, and observe #SafeDistancing requirements. To protect yourself and others around you, do put your mask back on as soon as you have finished smoking. From 19 Jun, Designated Smoking Areas along the Orchard Road No Smoking Zone can re-open with safe distancing measures. Smoking corners beyond the Orchard Road No Smoking Zone, can also re-open with the necessary safe distancing measures in place. www.nea.gov.sg/post-circuit-breaker-measures
From 22 Apr 2020, access to 4 popular markets will be restricted based on the last digit of patrons’ NRIC or FIN numbers, to ensure effective #SafeDistancing and safeguard public health. Patrons with NRIC/FIN ending with:
- an even last digit (0, 2, 4, 6, 8) can only visit on the even dates of the month
- an odd last digit (1, 3, 5, 7, 9) can only visit on the odd dates of the month
These 4 markets are Geylang Serai Market, Block 104/105 Yishun Ring Road (Chong Pang Market), Block 20/21 Marsiling Lane Market, and Block 505 Jurong West Street 52 Market. More information available at www.facebook.com/NEASingapore/posts/2589759427912055
If your parents or older relatives do their grocery shopping at these 4 popular markets, do share the guide (available in 4 different languages) with them! Download a copy from https://www.facebook.com/NEASingapore/posts/2590540227833975
Dine-in at #OurHawkerCentres resumes from 19 Jun! Whilst you may be excited to meet with your friends, limit the group to 5 people or less and continue to observe #SafeDistancing measures – use unmarked seats/tables, keep 1 metre apart from others, and only remove your masks when eating.
At our markets, continue to stand within the boxes marked on the floor, to maintain a safe distance. Access to the 4 popular markets will continue to be restricted based on the last digit of your identification number. More information available at www.nea.gov.sg/media/news/advisories/index/safe-management-measures-in-phase-2-at-hawker-centres-and-markets
Need your essentials? In addition to wearing a mask to buy essentials at the supermarket, schedule your grocery run on a weekday and avoid the peak periods, or opt for delivery instead. Let’s take #SafeDistancing seriously, and work together to stop the spread of COVID-19. #SGUnited
Planning dinner with your friends? Due to #SafeDistancing, there may be limited seating capacity at many places, so call in advance to make reservations first. Otherwise, opt for takeaway (bring your own containers!) or delivery 😊#SGUnited#FightCOVID19
#SafeDistancing applies everywhere – even when choosing fish and vegetables at the markets! If you have elderly neighbours or family members, help them with their marketing instead so that they can #StayHome and stay safe. #SGUnited
Only sit on seats without markings when dining in at #OurHawkerCentres to maintain #SafeDistancing. If the seating capacity is limited, #BringYourOwn clean containers and choose to take-out instead. Let’s unite to #FightCOVID19 together! 💪#SGUnited
Let’s remember to stay at least a metre apart from each other. We wouldn’t want all the effort and resources of the past few months to go to waste. Dining in at #OurHawkerCentres? Let’s not forget to #ReturnOurTrays and #BinOurTissues after enjoying the meal! #SGUnited#SafeDistancing#FightCOVID19