Что делать если нужно поставить какую-то 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
🌍 Earth’s gravity is just strong enough to keep an atmosphere and liquid water, but not so strong that gases like hydrogen escape quickly. This balance is rare among rocky planets in our Solar System. ✨
#earth⚡#planet⚡#gravity⚡#geography⚡#nature
👉subscribe Amazing Geography
👉more Channels
🌎 The Great Attractor is a mysterious gravitational anomaly in the universe, pulling our Milky Way and thousands of galaxies towards it at over 600 kilometers per second. This region lies about 150 million light-years away in the direction of the constellation Centaurus, but it is largely hidden by the dense dust and stars of our own galaxy, making its true nature still unknown. ✨
#space⚡#astronomy⚡#gravity
👉subscribe Interesting Planet
👉more Channels
🪐 The cosmic microwave background contains a hidden signature called the "Sachs-Wolfe effect," where variations in temperature are linked to the gravitational pull of massive structures like galaxy clusters. This effect, first detected in the 1990s using data from the COBE and WMAP satellites, shows how even the oldest light in the universe was influenced by the invisible gravity of objects such as the Coma Cluster and the Great Attractor, providing a glimpse into how matter was distributed across the cosmos more than 13 billion years ago. ✨
#cosmology⚡#gravity⚡#universe⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy cluster known as the Bullet Cluster (1E 0657-56), a cosmic collision has split ordinary matter—seen as hot X-ray gas—from invisible dark matter, which can only be traced by its gravity. By observing how light from background galaxies bends around the Bullet Cluster, astronomers have created detailed maps showing where dark matter gathers, making this system a real, visual proof that most of the universe’s mass is hidden and does not emit light. ✨
#darkmatter⚡#galaxies⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Astronomers have measured that the Coma Cluster—a giant gathering of thousands of galaxies—stays held together by vast amounts of dark matter, an invisible substance that can't be seen but adds enough gravity to keep the cluster from flying apart. Despite all the stars and gas we observe, dark matter in the Coma Cluster outweighs everything visible by more than five times, showing how this hidden ingredient shapes the largest structures in the universe. ✨
#darkmatter⚡#galaxies⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The spiral galaxy NGC 3198 has helped scientists map the mysterious effects of dark matter—a hidden substance that doesn't emit light, but has enough gravity to control how stars move far from the galaxy's center. By tracing the speeds of stars in NGC 3198’s outer edges, astronomers found they move much faster than visible matter alone can explain, revealing an invisible halo of dark matter wrapped around the galaxy. ✨
#darkmatter⚡#galaxies⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The supermassive black hole at the center of the Milky Way, Sagittarius A*, was observed by the GRAVITY instrument on the Very Large Telescope in 2018, revealing that blobs of hot gas orbit just outside its event horizon at about 30% the speed of light. This close-up look confirmed extreme gravity effects predicted by Einstein, and for the first time, scientists watched matter whip around a black hole in real time just kilometers from the point of no return. ✨
#blackholes⚡#gravity⚡#milkyway⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Astronomers have observed an unusual form of space-time distortion called "frame dragging" around the rapidly spinning black hole in the galaxy XTE J1550–564. Frame dragging is an effect predicted by Einstein’s relativity, where a rotating massive object actually twists nearby space and time, causing the orbits of matter and light around it to precess—showing in real life how intense gravity can physically drag space itself into motion. ✨
#wormholes⚡#spacetime⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2015, astronomers using the Hubble Space Telescope watched star light from behind the galaxy cluster Abell 3827 bend and split as it passed through the cluster, a real-life effect of space-time distortion called gravitational lensing. Gravity from massive clusters like Abell 3827 warps the space around them, so light takes curved paths and can appear as multiple, stretched images—direct evidence that space itself can be bent by gravity’s pull. ✨
#wormholes⚡#spacetime⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 On Jupiter, time actually ticks a little faster than on Earth! Because Jupiter is much less dense and has weaker gravity at its cloud tops, its gravitational pull slows time down less than Earth's gravity does—a real effect called gravitational time dilation, where clocks in stronger gravity run slower compared to those farther away from massive objects. ✨
#timedilation⚡#jupiter⚡#gravity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries