Что делать если нужно поставить какую-то 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
Making Singapore a liveable, inclusive and endearing home for all takes a collective effort. Learn how you can contribute to the Draft Master Plan 2025 and shape your future Singapore here: go.gov.sg/URADraftMasterPlan
#DMP2025
Infographics: @urasingapore
[JUST LAUNCHED] Join us in shaping our city in the Draft Master Plan 2025 Public Engagement!
Long-term planning has shaped the city that we live in today. Now, you too can play a part in making Singapore a more liveable, inclusive and endearing home.
We will be engaging Singaporeans over the next two years on various plans and the public engagement exercise will culminate in the Draft Master Plan 2025, which will guide Singapore’s development over the next 10 to 15 years.
Find out more at: https://go.gov.sg/DMP2025videotg
#DMP2025
Who says uncles can’t keep up? 🏙💪
Meet Team Strong Silvers, your friendly neighbourhood uncles who aren't just staying active; they inspire an entire community to move! Watch how this group of friends show us what ageing-in-place looks like - turning everyday spaces into pockets of connection.
Want more neighbourhoods like this? The URA Draft Master Plan 2025 is shaping spaces where we can all age strong and live well. Learn more: go.gov.sg/ExtraordinaryStoriesTG✨
#DMP2025#SpaceForOurDreams
Will Singapore ever run out of land? 👀
We get this question a lot—so we got Navin, our Urban Planner, to break it down for you. From sky gardens to underground links, see how we’re planning ahead to make room for all the things that matter—homes, recreation, green spaces, your dreams and aspirations. 🌇🌿
Share with us your ideal Singapore in the next 10 to 15 years here: go.gov.sg/URAPlannerExplainsTG and keep an eye out for our upcoming exhibition in June!
#DMP2025#SpaceForOurDreams
This is our type of ASMR. 😌
👣 Active Living: Move freely and with ease on walkable pathways.
🌻 Social Well-Being: Bond with your community in shared spaces.
🌳 Mental Wellness: Discover peaceful parks near home to relax and unwind.
☁️ Routine: Everyday wellness, wherever you are.
Check out our newest Urban Lab exhibition at: go.gov.sg/HealthyCitiesTG
Well-Being in the City: Innovating Healthy Living
📅: 1 Apr - 31 May 2025
📍: The URA Centre, Level 1 Atrium
#DMP2025#SpaceforOurDreams
Ever wondered who decides what gets built in Singapore? 🤔
It's not just professionals and government agencies—you can contribute too! Join Davina, our Urban Planner, as she unveils how the land planning process works in Singapore.
Got ideas to shape your neighbourhoods or workspaces? 💡 Visit go.gov.sg/URAPlannerExplainsTG to see what’s planned for the Draft Master Plan 2025 and share your thoughts!
#DMP2025#SpaceForOurDreams
Big things are happening at the Rail Corridor with new community nodes coming your way!
Think chill spots, and heritage gems getting a fresh spin. 🌿✨
Watch to see what’s shaping up, and swing by the 'From Rail to Trail' Rail Corridor Exhibition to check out more.
📅: Now till 28 Feb 2025
📍: URA Centre
👉 Share your ideas at: go.gov.sg/RCexhibitionTG
#SpaceForOurDreams#DMP2025
Take a stroll down the Rail Corridor with URA's Senior Director of Planning, See Nin, and wildlife documentary camerawoman, Evangelista, as they reveal how this 24km stretch of passageway was transformed from tracks 🛤 to trails 👣 – while preserving its distinctive character! This isn't just another makeover; we're talking about over 50 access points connecting neighbourhoods across our sunny island!
💭 The journey continues, and we want to hear from you! Join us at the Rail Corridor Exhibition happening from 17 Jan at the URA Centre! Find out more on go.gov.sg/RailCorridorTG
#DMP2025#SpaceForOurDreams
Swipe to see how Punggol Digital District is transforming into Singapore’s first smart district. With community spaces, green paths and integrated work-live-play environments, it’s taking urban living to the next level!
Read more at go.gov.sg/PDDarticleTG.
Keep a lookout for the Draft Master Plan 2025 exhibition happening in June, where we will be seeking your ideas on more business and job nodes across Singapore!
Image credits: JTC Corporation
#DMP2025#SpaceForOurDreams
Creating a more liveable, inclusive, and endearing Singapore — that’s the goal of the Draft Master Plan 2025, and we’ve made great strides this year. Here’s our 2024, wrapped!
For more info, visit go.gov.sg/URADraftMasterPlanTG
#DMP2025#SpaceforOurDreams
Imagine your future, supercharged ⚡🔋
Check out how plans for our Northern and Central areas' business nodes will mean even shorter trips to work, more innovative spaces to learn and collaborate, and lively, green neighbourhoods to live your best life!
Last chance to explore these transformations and more at our ‘Enabling Sustainable Growth: Shaping the Future of Work’ exhibition!
📅: Now till 3 Jan 2025
📍: URA Centre
👉 More info: go.gov.sg/FutureofWorkTG
#DMP2025#SpaceForOurDreams
Smarter. Faster. Greener.
Discover innovations that are shaping the future of last-mile deliveries. 💡
Singapore is shaping the future of last-mile deliveries with AI, robots and innovative designs. Don’t miss out on seeing it all in one place!
📅: Now till 25 Jan 2025
📍: URA Centre
👉 Free guided tours and more at:
go.gov.sg/DeliveringtheFutureTG
#DMP2025#SpaceForOurDreams