Что делать если нужно поставить какую-то 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
विकास पथ को गति दे रहे भारत के राष्ट्रीय राजमार्ग।। 🛣️
भारत के सड़क नेटवर्क के विस्तार के साथ-साथ प्रगति की यात्रा का गवाह बनें। यह परिवर्तन वास्तव में #NewIndia की गति और विकास का प्रमाण है।
#InfrastructureDevelopment
#Highway
Experience high-speed connectivity for industrial centres with the Nashik Phata – Khed Corridor!
Enhancing travel between Pune and Nashik along NH-60, this corridor reduces congestion around Pimpri-Chinchwad, fostering industrial growth and smoother transportation.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
Guwahati's connectivity gets a major boost with the new Northern Guwahati Bypass!
Upgrading the existing bypass and constructing a major bridge over the Brahmaputra, this project will significantly improve travel efficiency and support regional development.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
The Kanpur Ring Road project will complete the 6-lane National Highway Ring around Kanpur!
Enhancing traffic flow and reducing congestion, this project is set to transform Kanpur’s connectivity, making travel within the city and to other regions smoother and faster.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
Boost industrial connectivity with the Pathalgaon & Gumla sections of the Raipur-Ranchi National High-Speed Corridor!
Linking mining areas in Gumla, Lohardaga, Raigarh, Korba, and Dhanbad to industrial zones in Raipur, Durg, Bilaspur, and Bokaro, this project promotes faster, efficient transportation.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
Pilgrims can now reach Ram Mandir via the Ayodhya Ring Road!
This project facilitates quicker movement for devotees visiting the sacred site, enhancing the spiritual journey and supporting regional tourism and infrastructure development.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
Ensure smooth freight movement with the Tharad – Deesa – Mehsana – Ahmedabad National High-Speed Corridor!
This corridor links industrial regions in Punjab, Haryana, and Rajasthan to major ports in Maharashtra, enhancing logistics efficiency and boosting industrial growth.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
Unlock the North East with the Kharagpur-Moregram National High-Speed Corridor!
Connecting West Bengal, Odisha, and Andhra Pradesh to the North-East, this project will increase traffic capacity by over 5 times, promoting regional development and improving travel efficiency across these states.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
Travel faster to iconic landmarks with the Agra-Gwalior National High-Speed Corridor!
Enhancing connectivity to tourist hotspots like Taj Mahal, Agra Fort, and Gwalior Fort, this corridor will double traffic capacity and cut travel time by 50%.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
Experience seamless travel with 8 national high-speed road corridors spanning 936 km!
With an investment of Rs 50,655 crore, these corridors are set to revolutionize connectivity and boost economic growth across India.
#InfrastructureDevelopment#NewIndia
#TransformingIndia
India's National Highways - From Roadblocks To Road Wonders!
Witness the wide ride of progress as India's road network expands, solidifying its position as one of the largest in the world. This transformation is truly a testament to #NewIndia's growth and development.
#InfrastructureDevelopment
#Highway