Что делать если нужно поставить какую-то 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
🌟Thinking of applying for the IRAS scholarship?
Get insider tips from our current scholars to help with your application. ✍️ Don’t miss this opportunity to contribute meaningfully to Singapore’s economic and social growth. Apply to be an IRAS scholar at go.gov.sg/scholarapply by 31 March 2026.
#IRASscholarships#scholarships
Where tax builds tomorrow. 🇸🇬
Our scholars Nathaniel, Jing Rong, and Yern-Wei share about their journey in IRAS and how their work drives Singapore’s economic growth and inclusive society. Join us and discover diverse, purpose-driven careers that foster dynamic learning and collaborative innovation!
Watch the full video here: https://youtu.be/sHnS6XFP-HA?si=m-uuab47jrjnr47H
✍️ Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where every expertise matters. 💼
At IRAS, we bring together different disciplines and unique specialists to work on projects that drives Singapore’s economic growth. IRAS scholarships are open to students from diverse areas of study.
Watch the full video here: https://youtu.be/sHnS6XFP-HA?si=m-uuab47jrjnr47H
Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where tax builds tomorrow.💡
With pre-filled forms containing income details and tax reliefs, filing taxes is done in a matter of minutes. But what goes on behind-the-scenes to create this smooth taxpaying experience? Meet IRAS Director Leong Shi Wei, who leads multidisciplinary teams that oversee data policy, governance, and digital partnerships - making paying taxes a seamless and automated experience. Learn more about his work at IRAS here: https://go.gov.sg/iras-designing-the-tax-experience
Ready to collaborate with diverse teams on projects of national importance? 🇸🇬Apply to be an IRAS scholar today at go.gov.sg/scholarapply. Applications close on 31 Mar 2026.
#IRASscholarships#scholarships
Where every expertise matters.🧪
At IRAS, we bring together diverse and unique disciplines and specialists to drive projects that shape Singapore’s future. Meet Charmaine Tan, an IRAS scholar pursuing her Bachelor of Science in Life Sciences and Minor in Forensic Science, as she shares how her academic passion translates into meaningful impact.
Ready to put your expertise towards nation-building? 🌟 Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#IRASscholarships#scholarships
Where growth knows no limits. 🌱
What does it mean to be an IRAS scholar? Meet Shaine Goh (Software Engineer, Infocomm Division) whose journey with the IRAS Merit Undergraduate Scholarship turned her potential into real-world impact. 💼 From computing skills to transforming tax services, Shaine shows how innovation can reshape the taxpayer experience. Read her story: go.gov.sg/iras-shaine-goh
At IRAS, we invest in your personal growth so you can maximise your full potential. Ready to grow without limits? ✨ Apply to be an IRAS scholar today at go.gov.sg/scholarapply.
#scholarships#IRASscholarships
Where tax builds tomorrow.
IRAS scholarships are your gateway to a meaningful career that propels Singapore’s economic growth forward. Take your first step with us and unlock endless possibilities.
Ready to shape tomorrow? Learn more about life at IRAS at go.gov.sg/lifeatiras and visit go.gov.sg/scholarapply to apply to be an IRAS scholar via BrightSparks today.
#scholarships#IRASscholarships
🌐 As a Tax Director in IRAS’ Corporate Tax Division, IRAS scholar Joanne Tan refines tax laws and shapes policies that strengthen Singapore’s economic future, while leading a team of officers to discover the dynamic side of tax work. Learn more about her journey at IRAS here.
Apply for IRAS scholarships today at go.gov.sg/scholarapply
#lifeatIRAS#IRASscholarships#scholarships
Have questions about IRAS Scholarships? We’re here to answer them. 💬
Our scholarship application is now open, so don’t miss out! Apply today at go.gov.sg/scholarapply.
For more details, feel free to reach out to us at [email protected].
#IRASscholarships#scholarship#lifeatiras
📢 Calling all A-level/IB graduates and university students from all disciplines!
Catch a glimpse of life as an IRAS intern – follow our scholar Gerald Wong through his #dayinthelife.
Ready to make a difference? Join our future-ready #IRASFam and do work that matters in a collaborative, empowering environment. 🚀 Apply for IRAS scholarships at go.gov.sg/scholarapply or internships at www.careers.gov.sg today.
#lifeatIRAS#IRASscholarships