Что делать если нужно поставить какую-то 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 2021, scientists using the LIGO and Virgo detectors observed gravitational waves from a collision between two massive black holes named GW200129, located over 5 billion light-years away. What made this discovery unusual was the strong "precession" of the black holes’ orbits—a wobble much like a spinning top—which had never been clearly seen before, opening a new way to study how spinning black holes merge and ripple through the fabric of space. ✨
#gravitationalwaves⚡#blackholes⚡#space-time ⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2016, scientists using the Laser Interferometer Gravitational-Wave Observatory (LIGO) made history by detecting gravitational waves from the collision of two black holes over a billion light-years away. Gravitational waves are actual ripples in the fabric of space itself, created when massive objects like black holes or neutron stars crash together, letting astronomers "hear" cosmic events that were invisible before. ✨
#blackholes⚡#gravitationalwaves⚡#space-time ⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2023, astronomers announced the very first detection of gravitational waves coming from the collision of two supermassive black holes—giant black holes millions of times heavier than the Sun—located in distant galaxies. These faint ripples in space-time were picked up using pulsar timing arrays, which rely on ultra-precise measurements of radio pulses from rapidly spinning neutron stars, revealing a whole new side of the universe where invisible titans shape the cosmos with their dances and crashes. ✨
#gravitationalwaves⚡#blackholes⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2023, scientists using the Laser Interferometer Space Antenna (LISA) Pathfinder technology prepared for future space-based detection of gravitational waves—tiny ripples in space made by massive events like black hole collisions. Unlike Earth-based detectors, LISA will measure these waves from space, opening a new window to observe cataclysmic events in galaxies millions of light-years away and revealing secrets hidden by cosmic dust and distance. ✨
#gravitationalwaves⚡#blackholes⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In 2019, gravitational wave detectors LIGO and Virgo picked up GW190814—a signal from the merger of a black hole about 23 times the mass of the Sun and a mysterious compact object weighing just 2.6 solar masses. This lighter object is too heavy for known neutron stars but lighter than any confirmed black hole, creating a real cosmic mystery and challenging scientists to rethink what kinds of objects can exist in the universe. ✨
#gravitationalwaves⚡#blackholes⚡#mysteries⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2020, astronomers made a pioneering discovery by detecting gravitational waves from the merger of a black hole and a neutron star in a distant galaxy. Gravitational waves are ripples in space caused by massive objects accelerating or colliding, and finding this "mixed" merger—between a dense neutron star and a black hole—helped confirm that such pairs really exist and can dramatically reshape the universe. ✨
#gravitationalwaves⚡#blackholes⚡#neutronstars⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In July 2023, the NANOGrav collaboration announced the detection of a subtle, continuous "hum" of gravitational waves rippling through the Milky Way, likely created by pairs of supermassive black holes orbiting each other in distant galaxies. Gravitational waves are tiny ripples in space itself, first predicted by Einstein, and their detection with pulsar timing arrays—using rapidly spinning stars that act as cosmic clocks—opens a new era for exploring invisible giants and the history of galaxy mergers across the universe. ✨
#gravitationalwaves⚡#pulsars⚡#blackholes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In 2023, scientists using pulsars—ultra-dense, spinning stars that emit radio pulses like cosmic clocks—detected a faint background hum of gravitational waves rippling through our galaxy. These gravitational waves, created by supermassive black holes merging in distant galaxies, gently stretch and squeeze the fabric of space, opening an entirely new window into the universe’s most titanic collisions. ✨
#gravitationalwaves⚡#pulsars⚡#blackholes⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In 2015, the twin LIGO detectors in the United States made a groundbreaking discovery by directly detecting gravitational waves—tiny ripples in the fabric of space itself—caused by two black holes merging about 1.3 billion light-years away. This event, called GW150914, proved that space can literally shake, confirming a century-old prediction by Einstein and opening a whole new way to "listen" to the universe beyond just observing light or radio waves. ✨
#gravitationalwaves⚡#blackholes⚡#discovery⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2023, astronomers using gravitational wave observatories detected GW230307, a signal from the merger of two neutron stars in a distant galaxy. Neutron stars are the incredibly dense cores left behind after supernova explosions, and their collision sent ripples—gravitational waves—through space itself, allowing scientists to study the properties of matter squeezed far beyond anything found on Earth. ✨
#gravitationalwaves⚡#neutronstars⚡#collisions⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Some gamma-ray bursts last less than two seconds and are thought to result from the collision of two neutron stars—ultra-dense remnants of massive stars that pack more mass than the Sun into a space the size of a city. In 2017, the galaxy NGC 4993, about 130 million light-years away, was the site of such a collision, allowing astronomers to observe both gamma rays and gravitational waves from the same cosmic event—a rare glimpse into the most violent mergers in the universe. ✨
#gamma-ray ⚡#neutronstar⚡#gravitationalwaves⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2020, astronomers detected gravitational waves from the merger of two black holes with highly unequal masses—one about nine times heavier than the other—in a distant galaxy. This unusual event, named GW190814, created a final object weighing about 142 times the mass of our Sun, providing the first strong evidence for so-called "intermediate-mass" black holes that fill the mysterious gap between stellar and supermassive black holes. ✨
#gravitationalwaves⚡#blackholes⚡#discoveries⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels