Что делать если нужно поставить какую-то 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
🪐 In the heart of our galaxy, the supermassive black hole Sagittarius A* creates such intense gravity that time itself slows down near its edge—a real effect called gravitational time dilation. If you could hover safely just outside the black hole’s event horizon, minutes near this immense object would pass as hours or days for someone far away in space, making Sagittarius A* a true cosmic time-bender. ✨
#timedilation⚡#blackholes⚡#milkyway⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy M87, where astronomers captured the first-ever image of a black hole, time dilation is so intense near its event horizon (the boundary around a black hole from which nothing—even light—can escape) that an outside observer would see time appear to nearly stop for anything close to the edge. This real effect, predicted by Einstein’s theory of general relativity, means a clock near the event horizon would tick dramatically slower compared to one far away from the black hole. ✨
#timedilation⚡#blackholes⚡#relativity⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Time flows differently near massive cosmic objects like black holes—an effect known as time dilation. For example, close to the supermassive black hole Sagittarius A* at the center of our galaxy, clocks would tick slower than on Earth due to its intense gravity; astronauts orbiting just outside its event horizon would age less quickly than those far away, making time itself stretch in extreme environments. ✨
#timedilation⚡#relativity⚡#blackholes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 Deep space travelers will experience time differently than people on Earth—a mysterious effect called time dilation. If astronauts took a fast journey to the star Sirius (8.6 light-years away) on a spaceship moving near the speed of light, their onboard clocks would run much slower than those back home, so they would age less during the trip—even while years passed on Earth. This real phenomenon comes straight from Einstein’s theory of relativity and shows how speed itself can turn space voyages into journeys through time. ✨
#timedilation⚡#relativity⚡#spaceships⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 1977, the Voyager 1 spacecraft passed near Jupiter, and its onboard clocks experienced a tiny but measurable time dilation due to the planet's gravity. This real effect, predicted by Einstein's theory of general relativity, means time ticked just a little slower for Voyager as it flew close to massive Jupiter than it did for clocks far from the giant planet—showing that even in our own solar system, gravity can subtly warp the flow of time. ✨
#timedilation⚡#Jupiter⚡#relativity⚡#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
🪐 On Mercury, time passes at a different rate than on Earth because the planet orbits much closer to the Sun and feels stronger gravity—a real effect called time dilation. According to Einstein's theory of relativity, stronger gravity slows down the flow of time, so a clock sitting on Mercury's surface would actually run slightly slower than an identical clock on Earth, making time itself stretch differently across the solar system. ✨
#timedilation⚡#relativity⚡#mercury⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The twin pulsars PSR J0737−3039A and B, located about 2,400 light-years away in the constellation Puppis, are a real-world testing ground for time dilation in space. As these two ultra-dense neutron stars orbit each other at high speeds and within extremely strong gravitational fields, their clocks run at noticeably different rates than those on Earth—showcasing how both high speed and intense gravity stretch and slow down time, just as predicted by Einstein’s theory of relativity. ✨
#timedilation⚡#pulsars⚡#puppis⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Inside the galaxy NGC 4995, astronomers have used its rapidly spinning star clusters to explore time dilation—where time actually passes more slowly the faster you move. According to Einstein’s relativity, this means stars racing around the galaxy’s center age just a tiny bit less than similar stars sitting still, a real effect measured with ultra-precise clocks and confirmed by observations of high-speed cosmic objects. ✨
#timedilation⚡#relativity⚡#NGC4995⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 1971, the astronauts of Apollo 15 left a small aluminum device called a retroreflector on the surface of the Moon, which allows scientists to precisely measure distance by bouncing laser beams from Earth. Over decades, these experiments have shown that time passes ever so slightly faster for the reflector on the Moon than for clocks on Earth, due to weaker lunar gravity—a subtle, real-world example of gravitational time dilation across the solar system. ✨
#timedilation⚡#moon⚡#apollo⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 When astronauts journeyed to the Moon aboard Apollo missions, their clocks actually ticked a tiny bit faster than those left on Earth, thanks to time dilation caused by weaker gravity. This real effect, predicted by Einstein’s theory of general relativity, means that even on the lunar surface—where gravity is only about one-sixth of Earth's—time stretches ever so slightly, making lunar explorers age just a bit more quickly during their stay than their counterparts on the ground. ✨
#timedilation⚡#apollo⚡#moon⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Time dilation in space means that time can pass at different rates depending on speed or gravity. On the fast-moving Juno spacecraft orbiting Jupiter, the combination of high speed and weaker gravity actually causes time to move a tiny bit faster for the probe than for people on Earth—a real-life effect of Einstein’s theories now measured using atomic clocks on robotic explorers across the solar system. ✨
#timedilation⚡#relativity⚡#junomission⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels