Что делать если нужно поставить какую-то 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 rustic handmade ceramic mug filled with rich hot chocolate, topped with melting marshmallows and a dusting of cocoa powder. The mug sits on a weathered wooden table beside an open book and a softly folded knitted blanket. Gentle morning light filters through a window, creating soft shadows and highlighting the steam rising from the drink. Cozy, atmospheric mood, hyper-detailed, shallow depth of field, 8k resolution, warm tonal palette, lifestyle photography, no text or logos visible. --ar 3:4 --v 7
#food
📣Midjourney prompts
Нужно почаще делать. Крайне рекомендую 👍🏼
isometric photography of delicious baguette sandwich lay on flat ground in studio, it contain (lettuce, sliced tomato and cucumber and salami sausage, melted cheese), solid dark red background, white studio lighting, minimalistic product photography, natural color and lighting, 80mm shot, high resolution --ar 2:3 --v 7
#food
📣Midjourney prompts
An ultra-realistic photograph of the Mocha coffee cocktail in its signature glass, with layers of cream and caramel on top. The drink is placed on a wooden tray surrounded by scattered brown coffee beans. In front of it lies one small bowl filled with espresso. Soft lighting highlights the texture of each element, creating a warm atmosphere that suggests comfort without overwhelming attention to detail --v 6.1 --ar 71:128
by queen4497
#food
📣Midjourney prompts
Ultra-realistic, 8K, highly detailed cinematic shot of tiny humanoid workers (6 inches tall) struggling to transport a massive pomegranate on a miniature wooden truck. Some tiny workers push the giant fruit up a ramp, while others tie tiny ropes to secure it in place. The mini truck's wheels sink slightly under the fruit’s weight, showing the immense size of the pomegranate. A tiny driver sits inside the miniature truck cabin, steering carefully as the vehicle moves down a narrow dirt road surrounded by lush trees. The background features more tiny workers following the truck, carrying baskets of smaller pomegranates. Photorealistic lighting, cinematic depth, and immersive storytelling. 8k --ar 9:16 --v 6.1
by thetrailerspk_66832
#food
📣Midjourney prompts
A highly realistic advertising scene featuring a plastic cup with a straw, for decoration, on the rim is two leaves green of brown sugar. .The upper section of the cup is filled with fresh jus green tea green matcha and coco liquid with vanilla. The middle section contains a smooth, slushy iced drink made from a blend of liquid of green tea green matcha , The bottom section of the cup features A realistic scene of bubbles black café boba. This plastic cup is surrounded by a Half a piece of coconut with its green leaves, and on the other side of the plastic cup, a purple jasmine flower, and the scene is presented in an advertising and professional manner. . The entire scene is captured using professional advertising techniques and a high-quality camera, delivering a visual presentation with the highest level of realism. The background is an attractive pink shade --v 6.1
by khabbaz
#food
📣Midjourney prompts
A lavish macro picnic scene with a wicker basket filled with freshly baked baguettes, arranged beside a silver fruit tray holding pomegranates, pears, and grapes. The fruits' vibrant colors contrast against the ruby red blanket, while scattered rose petals and lavender sprigs add a touch of romantic charm. The vibrant red trees in the background create an opulent autumn backdrop, bathed in soft, warm light. Captured in high-definition photography, emphasizing textures, colors, and natural elegance --ar 3:5 --v 6.1
by newyrok1976
#food
📣 Midjourney prompts
A bowl of chicken and vegetable soup with green oil, in front of which is a colorful fabric --v 6.1 --ar 21:32
by queenbee_67685
#food
📣 Midjourney prompts
Create a vivid, high quality image on a white background of the following items on a plate: chocolate, grapes, onions, garlic, avocado, citrus, coffee, macadamia nuts, and walnuts --v 6.1 --ar 2:3
by hoot2055
#food
📣 Midjourney prompts
Create a cinematic fairytale-style photo project showcasing an entire city made from Mamaliga (polenta), inspired by the traditional Orheiul Vechi landscape. The scene features enchanting hills crafted from the vibrant yellow texture of Mamaliga, with rivers of liquid sour cream winding through the terrain. The city is alive with whimsical details: trees formed from delicate slices of garlic and charming houses built from soft cottage cheese. Natural colors enhance the realism, with diffused sunlight softly highlighting every texture, creating a vivid, magical Moldovan atmosphere that balances realism with a fairytale-like wonder. Format the image in 9:16 ratio for reels, capturing the vertical majesty of the landscape --v 6.1
by kate12131415
#food
🔱 Prompt collection
Blueberry milkshakes in a round serving glass table background , side ANGLE full glass view clear composition on light wooden table background, bright daylight, on the middle of the table the style of Hasselblad X2D, following rule of third, vibrant color, no blur --s 50 --v 6.1
by azzholk007
#food
🐝 Prompt collection