Что делать если нужно поставить какую-то 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
🌎 The Hubble Deep Field image, captured in 1995, revealed thousands of galaxies in a tiny, seemingly empty patch of sky. Each pinpoint of light is a galaxy containing billions of stars, some over 12 billion light-years away. ✨
#astronomy⚡#hubble⚡#universe
👉subscribe Interesting Planet
👉more Channels
🪐 In 2015, scientists using the Hubble Space Telescope watched a star named F01004-2237 in a distant galaxy vanish from view, providing rare evidence of a star being swallowed whole by a supermassive black hole. As the black hole tore the star apart, it produced a dramatic flare of light called a tidal disruption event—an intense cosmic signal that lets astronomers witness the hidden power of black holes at work. ✨
#blackholes⚡#hubble⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the galaxy NGC 3706, astronomers using the Hubble Space Telescope have found a mysterious, perfectly round disk of stars swirling close to a supermassive black hole. This dense, circular ring is less than 200 light-years across and orbits so quickly that it reveals the incredible gravitational pull black holes can exert, yet scientists are still puzzled by how such a perfectly shaped stellar disk could form so close to the heart of a galaxy. ✨
#blackholes⚡#hubble⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In 2012, astronomers using the Hubble Space Telescope discovered a supernova named SN Primo in the distant galaxy SXDS-1069, whose light traveled over 9 billion years to reach Earth. This explosion offers a view into the universe’s youth, revealing that supernovae have been enriching galaxies with heavy elements like iron and oxygen since the cosmos was less than half its current age—a process crucial for forming new stars and planets. ✨
#supernovae⚡#hubble⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the spiral galaxy NGC 2525, a supernova explosion imaged by the Hubble Space Telescope in 2018 briefly outshone all the other stars in its galaxy combined. Supernovae are the final, colossal explosions of massive stars, releasing enough energy in just weeks to equal the total output of our Sun over billions of years, and leaving behind exotic remnants like neutron stars or black holes. ✨
#supernovae⚡#galaxies⚡#hubble⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In 2022, astronomers used the Hubble Space Telescope to identify a fast radio burst originating from a galaxy called WISEA J071634.59–190039.2, located about 6 billion light-years from Earth. This pinpointed location helps scientists study the environments where these ultra-short, powerful flashes of radio energy are born, revealing new clues about the mysterious origins of fast radio bursts across the cosmos. ✨
#fastbursts⚡#hubble⚡#galaxies⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The distance between Earth and the edge of the observable universe is about 46.5 billion light-years—meaning the furthest galaxies seen by the Hubble Space Telescope, like GN-z11, are so distant that their light has taken over 13 billion years to reach us, yet the universe has expanded even farther in that time. This immense scale exists because space itself stretches as light travels, making cosmic distances far greater than the simple time since the Big Bang would suggest. ✨
#spacedistances⚡#cosmology⚡#hubble⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy UDFy-38135539, discovered using the Hubble Space Telescope, is among the most distant objects ever detected—its light began its journey toward Earth more than 13 billion years ago. Seeing UDFy-38135539 means observing a galaxy as it existed when the universe was just a few hundred million years old, allowing astronomers to study the very dawn of galaxy formation. ✨
#galaxies⚡#hubble⚡#cosmicdawn⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The galaxy NGC 1300, located about 61 million light-years away in the constellation Eridanus, features a spectacular "barred spiral" shape, with a bright central bar of stars stretching across its core and sweeping spiral arms extending outward. Unlike typical spirals, this central bar channels gas inward, helping trigger bursts of star formation and giving NGC 1300 its unusual, grand design—making it one of the best examples of a cosmic structure shaped by galactic dynamics rather than collisions. ✨
#galaxies⚡#structures⚡#hubble⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In the spiral galaxy NGC 3147, astronomers have discovered a supermassive black hole encircled by a disk of gas that defies expectations—it's thin and spinning at nearly the speed predicted for much larger, brighter disks found around actively feeding black holes. This surprising find, made with the Hubble Space Telescope, shows that even "starving" black holes can maintain disks behaving like those from the most powerful galactic cores, challenging what scientists thought they knew about black hole feeding habits. ✨
#blackholes⚡#hubble⚡#galaxiess⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels