Что делать если нужно поставить какую-то 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
🪐 At the center of the elliptical galaxy Abell 2261, astronomers discovered one of the largest galactic cores ever observed—so vast and diffuse that it raised the question of whether a supermassive black hole had vanished from sight. This mysterious "missing black hole" has led scientists to wonder if extreme interactions in this galaxy could have warped space-time so severely that the black hole—and its surrounding region—may have been ejected or displaced, providing a real-world example of how powerful gravity can dramatically reshape the structure of space itself. ✨
#wormholes⚡#spacetime⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The closest real parallel to a "wormhole" in our universe can be seen in the power of gravitational lensing, such as what occurs in the galaxy cluster Abell 370. Here, the cluster's immense gravity bends and stretches the path of light from distant galaxies, acting like a natural lens and showing how space-time itself can be warped and twisted on a cosmic scale—a vivid example of how gravity can create real space-time distortions in the universe. ✨
#wormholes⚡#spacetime⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The idea of wormholes comes from real equations in Einstein's theory of general relativity, which describes how gravity bends space and time. Some scientists believe that extreme cosmic objects like the supermassive black hole Sagittarius A* at the center of our Milky Way could, in theory, warp space-time so much that shortcuts—wormholes—might exist, although none have ever been found. The bending of light and matter near these black holes is a real example of how space itself is stretched and twisted by gravity's power. ✨
#wormholes⚡#spacetime⚡#blackholes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Just outside the event horizon of the supermassive black hole in galaxy NGC 1365, time slows significantly due to the black hole’s intense gravitational pull—a phenomenon called gravitational time dilation. For an observer far from NGC 1365, minutes near the black hole’s edge could translate into hours or even days in regular space, showing how extreme environments can dramatically stretch the flow of time itself. ✨
#blackholes⚡#spacetime⚡#relativity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy cluster MACS J1206.2-0847, astronomers have mapped dramatic distortions of space-time caused by the cluster's enormous mass. This real effect, called gravitational lensing, bends and magnifies the light from even more distant galaxies behind it, turning MACS J1206.2-0847 into a cosmic lens that reveals objects otherwise hidden from our view. ✨
#spacetime⚡#mysteries⚡#lensing⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In 2019, astronomers using the Event Horizon Telescope observed the effects of extreme space-time distortion around the supermassive black hole in galaxy M87. The light from matter spiraling into this black hole was bent into a bright ring, revealing how gravity can warp space itself and create the famous "shadow"—a real demonstration of space-time being twisted by an enormous mass. ✨
#wormholes⚡#spacetime⚡#blackhole⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Einstein’s theory of relativity predicts dramatic space-time distortions in the violent heart of the galaxy M87, where its supermassive black hole bends not just light, but alters the very flow of time itself. As matter spirals inward, space-time warps so much that signals escaping from near the event horizon—the point of no return—are stretched and delayed, making M87’s core a real example of nature’s most extreme distortions. ✨
#wormholes⚡#spacetime⚡#relativity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Space-time, the "fabric" that weaves together space and time, is not always smooth—giant objects like the supermassive black hole at the center of our galaxy, Sagittarius A*, warp and stretch it so much that both light and time bend around them. These real cosmic distortions, predicted by Einstein’s theory of general relativity, are seen as stars orbit that black hole on paths twisted by its immense gravity, giving us direct evidence that space itself can be bent and curved by massive objects in the universe. ✨
#wormholes⚡#spacetime⚡#relativity⚡#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
🪐 The speed of light acts as the ultimate speed limit in our universe—no information or object can travel faster than 299,792 kilometers per second, not even the most powerful pulses from the Crab Pulsar in the heart of the Crab Nebula. This constant speed is what lets astronomers measure vast cosmic distances, and it’s the reason we see stars, galaxies, and even supernova explosions like SN 1987A as they were in the past, not as they are right now. ✨
#speedoflight⚡#spacetime⚡#distances⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2023, astronomers used the gravity of the massive galaxy cluster SMACS J0723.3–7327 to create a powerful "gravitational lens," sharply magnifying and stretching light from galaxies over 13 billion light-years away. This natural lens effect, where space-time bends around clusters and distorts the background like a cosmic funhouse mirror, provides one of the clearest real-world examples of how gravity can twist the fabric of the universe and reveal objects otherwise hidden from view. ✨
#wormholes⚡#spacetime⚡#lensing⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels