Что делать если нужно поставить какую-то 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 can’t leave out the signature carrot cake when talking about #OurHawkerCulture, and no, we don’t mean the dessert! Also known as Chai Tow Kway, this savoury dish is made from rice flour and radish.
✨ Ever wondered about the name 'Chomp Chomp Food Centre'? It's a nod to “忠忠” – symbolising loyalty and righteousness. 🍲 Share this with your favourite foodies!
#OurHawkerCulture#OurHawkerCentres
The dilemma for any meal! Which button are you pressing today? 🤔
Share your favourite hawker stalls in the comments and tag your foodie friends!
#OurHawkerCulture#OurHawkerCentres
Today is the first anniversary of the UNESCO inscription for Singapore’s Hawker Culture, so let’s come together to celebrate, support, and safeguard #OurHawkerCulture!
#DidYouKnow many of our hawker dishes originated from the food cultures of different immigrant groups who settled in Singapore? Over time, they have evolved to become the distinctive local dishes that we love, and form an important part of our food heritage.
Head down to your favourite hawker stall this week to show your support!
#DidYouKnow then Prime Minister Lee Kuan Yew laid the foundation stone for Geylang Serai Market back in 1963? It was rebuilt in 2009 with its architecture inspired by the Malay community’s cultural heritage.
As part of the efforts to safeguard our #OurHawkerCulture, we want to hear from you about what you hope to see in #OurHawkerCentres of the future. Tell us your views and ideas at https://go.gov.sg/sghf-form by 31 Jan 2021, and stand a chance to win a limited edition #OurHawkerCulture CEPAS card. Terms & conditions apply: https://go.gov.sg/sthctc
🍜 Ever wonder how the monthly price-based tender system for hawkers work?
Every month, NEA offers vacant food and market stalls through open tenders. This ensures stalls are allocated fairly and transparently. When new hawkers successfully bid for a stall, their rent for the first three years will be based on their bid. At the end of the 3-year tenancy term, the rent is then adjusted over time to match the Assessed Market Rent (AMR), which is determined by an independent valuation. This AMR takes into account various factors such as footfall, stall sizes, and tendered stall rentals at the hawker centres. The median AMR for non-subsidised cooked food stalls has remained constant since 2019 at about $1,200 per month.
📢 While past tenders may be considered in AMR, extremely high tender bids will not be considered in the valuation of the AMR.
Curious about becoming a hawker or just want to learn more? Click here: go.gov.sg/info-stallholders
#SupportOurHawkers#OurHawkerCulture#OurHawkerCentres
In 2020, Singapore’s hawker culture was officially inscribed onto the UNESCO Representative List of Intangible Cultural Heritage of Humanity. But let's not stop there!
Let’s continue to #SupportOurHawkers and keep #OurHawkerCulture thriving for generations to come.
P.S. Don’t forget to use your CDC vouchers before they expire! Check out the participating stalls at #OurHawkerCentres here: gowhere.gov.sg/cdcvouchersmerchants
🍜 Supporting Our Hawkers: The Government sets policies to support our hawkers and provide them with a conducive operating environment, to ensure that they are able to provide Singaporeans with affordable food at #OurHawkerCentres.
You can #SupportOurHawkers too! Visit your favourite stall or try new ones today.
P.S. Don’t forget to use your CDC vouchers before they expire on 31 Dec 2024 (Tue)!
#OurHawkerCulture
Hawker culture is, and will always be, an integral part of the Singapore culture. Read our fellow Singaporeans’ thoughts on #OurHawkerCulture here: www.oursgheritage.sg/support-hawker-culture/
❤️#UniquelySingapore
#HawkerHeritage📢 Originally the Seng Poh Road Market in 1951, Tiong Bahru Market served as a bustling centre for the community. Next time you’re there for a meal, don’t forget to soak up the history & nostalgia!
#OurHawkerCulture#OurHawkerCentres