Что делать если нужно поставить какую-то 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
#PPOD: Titan's Surface 🌕
The atmosphere of Titan, one of Saturn’s moons, appears similar to that on Earth about 3.5 billion years ago, before life appeared.
After a seven-year journey on board the Cassini spacecraft, ESA’s Huygens probe reached Titan’s surface, marking the most distant landing ever achieved by a spacecraft. During the descent, its cameras collected data on the dense atmosphere and took the first-ever images of the surface.
These revealed an extraordinary world with lakes, islands, and erosion features similar to those that shape our planet, confirming that liquid methane once flowed there. Methane on Titan is found in liquid form, not as a gas, due to the intense pressure and cold temperatures, about –180° C.
Credit: esaNASA
Source: @SETIInstitute
@EverythingScience
#PPOD: Deimos Before Sunrise 🌄
NASAPersevere captured this view of Deimos, the smaller of Mars' two moons, shining in the sky at 4:27 a.m. local time on March 1, 2025, the 1,433rd Martian day, or sol, of the mission. In the dark before dawn, the rover's left navigation camera used its maximum long-exposure time of 3.28 seconds to capture 16 individual shots, which were combined into a single image that was later sent to Earth. In total, the image represents an exposure time of about 52 seconds.
The low light and long exposures add digital noise, making the image hazy. Many of the white specks seen in the sky are likely noise; some may be cosmic rays. Two of the brightest white specks are Regulus and Algieba, stars that are part of the constellation Leo.
"Woodstock Crater," at center right, is roughly a half-mile (750 meters) away from the rover. At the time, Perseverance was en route to "Witch Hazel Hill."
Credit: NASANASAJPLCaltech
Source: @SETIInstitute
@EverythingScience
#PPOD: The Eye of the Crater 👁️
A vast cavity on the Red Planet looks back at ESA TGO with an icy stare. The crater is located in Utopia Planitia, the largest known impact basin in the Solar System, with a diameter of roughly 3,300 km, or twice the size of Earth’s Sahara Desert from north to south.
This remnant of an ancient impact is just one of the many scars asteroids have inflicted upon the Red Planet. Water, volcanoes, and impacts from asteroids shaped the Martian surface in the ancient past. Mars is currently a cold, dry desert.
This view from CaSSIS shows a crater approximately eight kilometres in diameter with material ejected in a manner that scientists believe suggests the presence of water ice. When the asteroid hit this region of Mars, the water ice melted, and a mix of liquid water and dust rock was propelled from the top layers.
The smooth appearance of the crater is consistent with other features in the region, which have evidence of a water-ice history. Zooming into the crater, it is possible to see streaks on the walls of the crater, showing evidence of landslides, and ripples sculpted by the wind.
Credit: ESA/ TGO/CaSSIS
Source: @SETIInstitute
@EverythingScience
#PPOD: Martian Winter Wonderland ❄️
This sweeping view along a rusty red ridge and into a crater showcases the exquisite beauty of icy, layered terrain in the south polar region on Mars.
The High Resolution Stereo Imaging camera onboard ESA’s Mars Express captured this frosty scene in the Ultimi Scopuli region near the south pole of Mars on 19 May 2022. At this time, it was southern hemisphere spring, and ice was starting to retreat. Dark dunes began to peak through the frost, and the elevated terrain appears ice-free.
Credit: esaDLR enFU Berlin
Source: @SETIInstitute
@EverythingScience
#PPOD: Neptune 🔵
NASAVoyager 2 made its closest approach to #Neptune in 1989, flying by 4,950 km above its cloud tops. It is still the only spacecraft to have visited the planet! The mission revealed 6 new moons, rings, and geysers erupting from the moon Triton. This Voyager 2 image of Neptune, processed by Kevin Gill, was captured on Aug. 31, 1989.
Credit: NASANASAJPLCaltech / Kevin M. Gill
Source: @SETIInstitute
@EverythingScience
#PPOD: Curiosity Sends Holiday Postcard from #Mars🌄
Team members working with NASA’s MarsCuriosity created this “postcard” by commanding the rover to take images at two times of day on Nov. 18, 2025, spanning the 4,722nd and 4,723rd Martian days, or sols, of the mission.
The panoramas were captured at 4:15 p.m. on Sol 4,722 and 8:20 a.m. on Sol 4,723 (both at local Mars time), then merged together. Color was later added for an artistic interpretation of the scene, with blue representing the morning panorama and yellow representing the afternoon one. The resulting “postcard” is similar to ones the rover took in June 2023 and November 2021. Adding color to these kinds of merged images helps different details stand out in the landscape.
Credit: NASANASAJPLCaltech
Source: @SETIInstitute
@EverythingScience