Что делать если нужно поставить какую-то 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
A light beige sphere rolling on the edge of an abstract golden arch, a giant pastel sphere, minimalist sculptural forms geometric objects composition, rendered in the style of Cinema4D, a light green background. Cinema4D rendering, close-up crop view, high resolution, macro photography, detailed textures --ar 2:3 --v 7
#sculpture
📣Midjourney prompts
A 3D fragment of rugged limestone floating in mid-air, covered with green moss, pale pink and orange corals, lichen, translucent quartz crystals, wildflowers with light blue petals, clean white background, soft warm natural lighting, photorealistic render, Octane Render, Cinema 4D --ar 3:4 --raw --v 7 --draft
by u4777486387
#sculpture
📣Midjourney prompts
A surreal collage of Plato and Aristotle floating in deep space, surrounded by glowing galaxies, cosmic nebulae, and celestial bodies. The background is an optical illusion of wavy black-and-white lines, blending into the cosmic void, creating a hypnotic, dreamlike atmosphere. A bold, glowing sun or planet in vibrant orange contrasts with the monochrome waves. Floating ancient Greek sculptures of Plato and Aristotle appear weightless, surrounded by philosophical symbols, sacred geometry, and ethereal cosmic dust. A mix of classical art, futuristic surrealism, and optical illusion, ultra-detailed, mesmerizing, and immersive --v 6.1 --ar 2:3 --s 50
by u8959768711
#sculpture
📣Midjourney prompts
an abstract shiny glimmering oblong metal goopy object floating in the middle of a dark sand dune with primary light focusing on the object --v 6.1
by formula1345
#sculpture
📣Midjourney prompts
Hyperrealistic photograph of a classical Greek marble statue with damaged smoothed face. The statue is positioned against a black background. The interplay of light highlights the texture of the statue and the damage give a dark gritty vibe --ar 4:5 --style raw --p vh9rjv1 --s 150 --v 6.1
by liamdomonkos
#sculpture
📣 Midjourney prompts
ea jar, Chinese style, divine phoenix decoration, hotel shelf, decoration, three-dimensional relief, white jade texture, transparent, elegant details --ar 1:2 --v 6.1
--
Sculptures with the theme Classic of Mountains and Rivers --ar 2:3 --v 6.1
by angus6930
#sculpture
📣 Midjourney prompts
Two large rocks in the shape of human heads, they look at each other and smile, a crescent moon between them, a dark blue sky, night photography, in the style of Aerial Photography, in the style of Wes Anderson, in the style of David LaChapelle, cinematic, shot on a film camera, Kodak film stock. --ar 105:128 --v 6.1
-
Two rock formations shaped like a woman's shoulders, a crescent moon in the dark blue night sky, in the style of Vincent Munier --ar 105:128 --v 6.1
by mr-indolent
#sculpture
📣 Midjourney prompts
A conceptual stack of stone building bricks, concrete and timber. It is set against a solid brown background to highlight the contrast between the diffeent objects and background. This art piece conveys creativity through geometric shapes and textured surfaces --v 6.1 --ar 57:85
by mr-indolent
#sculpture
📣 Midjourney prompts
thin sheet of glass monument standing upright in a black stone query. evening light reflecting from the glass onto the stones and creates rainbow like colors. the glass is about 50% of the image. in the style of a product art shooting --ar 3:4 --v 6.1
by timo_weiss
#sculpture
📣 Midjourney prompts
🧘Отдохнув от гаджетов и соцсетей, бесконечно понимаешь, сколько же в нашей жизни информационного и визуального мусора.
Минимализм во всём так прост и одновременно недосягаем.
an Majestic statue of Buddha, in the style of iris van herpen, franciszek starowieyski, peter holme iii, graceful movements, national geographic photo, caravaggesque chiaroscuro, landscapes in motion --c 20 --ar 3:4 --q 2 --style raw --sref 492309580 --p zww2nvy oiwf4m5 --s 1000 --v 6.1
by zhya666
#sculpture
📣 Midjourney prompts
A serene classical sculpture of a woman's head with closed eyes, adorned with soft, delicate pink flowers. The flowers gently float around her head, as if suspended in mid-air. The background is a minimalist light pastel blue, creating a dreamy, ethereal atmosphere. The entire scene should evoke a sense of calm, blending traditional art with modern aesthetics, featuring a balance between solid marble-like textures and the delicate, airy nature of flower petals --v 6.1
-
A beautiful woman Greek statue-like head, holding a rose in her hand, facing the camera, with her blonde hair in an updo, in the style of David LaChapelle and Mapplethorpe, a collage --v 6.1 --ar 7:8
by velskaa, cherryoasis
#sculpture
📣 Midjourney prompts