Что делать если нужно поставить какую-то 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
Nubeo и Atari выпустили часы Automatic Atari Asteroids 45th Limited Edition
Дизайн часов отсылает к классической игре Asteroids: секундная стрелка выполнена в форме треугольного космического корабля, а две летающие тарелки являются соответственно часовой и минутной стрелками.
Часы выпущены в пяти расцветках, по 125 экземпляров каждой, но весь тираж уже, увы, распродан по предзаказам.
#Asteroids#Atari#Nubeo
NASA probe will study Jupiter's Trojan asteroids
NASA launched a first-of-its kind mission to study Jupiter's Trojan asteroids
#News#Reuters#NASA#Jupiter#Asteroids
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
🪐 Asteroid (2015) BN509, a giant space rock measuring about 200 meters wide and 400 meters long, speeds past Earth with a shape resembling a giant peanut. Its close flyby in 2017 brought it within just 14 times the distance to the Moon, and radar imaging revealed its rapid rotation and elongated, tumbling motion—features that could make its path unpredictable if nudged by gravity. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
👉more Channels
🪐 The asteroid (29075) 1950 DA stands out not only for its size but for its unique structure—it’s held together mostly by the tiny forces between individual grains, known as van der Waals forces, rather than by its own gravity. This means that if 1950 DA ever impacted Earth, its loosely-bound material could break apart differently than a solid rock, making its potential effects more unpredictable compared to typical asteroids. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
🪐 The asteroid 1950 DA, about 1 kilometer wide, is hurtling through space with an orbit that brings it close to Earth every few decades. Scientists monitor it closely because its surface is so loosely held together by gravity that only tiny forces—like sunlight pressure—keep it from flying apart, making it a uniquely fragile but potentially dangerous near-Earth object. ✨
#asteroids⚡#hazards⚡#space⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos
👉subscribe Universe Mysteries
🪐 The asteroid 99942 Apophis, discovered in 2004, is a near-Earth object about 340 meters wide that will make an extremely close pass by Earth in 2029—closer than some satellites! Though it once raised fears of an impact, precise tracking shows it will safely miss us, offering astronomers a rare chance to study such a large asteroid up close as it sweeps just 31,000 kilometers above our planet. ✨
#asteroids⚡#nearEarth⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 The asteroid (136617) 1994 CC is a rare triple system, meaning it consists of one main asteroid about 700 meters wide and two smaller moons orbiting it. This near-Earth object follows a path that occasionally brings it close enough to be watched by planetary defense teams, as its complex system could create unpredictable trajectories in the event of a gravitational nudge. ✨
#asteroids⚡#spacehazards⚡#astronomy⚡#nasa⚡#galaxy⚡#stars⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 In the constellation Ophiuchus, the asteroid 101955 Bennu harbors boulders on its surface that are actually fragments from a much larger parent asteroid, dislodged by ancient cosmic impacts. Analysis of samples returned by NASA’s OSIRIS-REx mission revealed minerals that interacted with liquid water billions of years ago, revealing Bennu as a time capsule from the dawn of the solar system. ✨
#Bennu⚡#asteroids⚡#OSIRISRex
👉subscribe Universe Mysteries
🪐 Asteroid (1862) Apollo is one of the first discovered "Apollo-type" near-Earth asteroids, regularly crossing Earth's orbit on its journey around the Sun. Measuring about 1.5 kilometers wide, Apollo's path is closely monitored because its changing orbit brings it close enough to qualify as potentially hazardous—a reminder of why astronomers track even ancient space rocks to protect our planet from unexpected encounters. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 In 2013, the small asteroid 2012 DA14, about 30 meters wide, passed just 27,700 kilometers above Earth—closer than many weather satellites. Unlike much larger objects, even an asteroid this size could cause massive regional destruction if it ever struck, which is why astronomers keep careful watch for these smaller, fast-moving near-Earth objects. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Asteroid (2015) BP513 is a near-Earth object discovered in 2015, which measures around 440 meters across and has an orbit that occasionally brings it within a few lunar distances of our planet. While it poses no immediate threat, its path is tracked closely by astronomers, since an object of this size could cause severe regional damage if it ever collided with Earth—a reminder of why the study and monitoring of such asteroids are vital for planetary defense. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Asteroid (86039) 1999 NC43 is a massive near-Earth object more than 2 kilometers wide that follows a path bringing it close to our planet's orbit. Its size means that if it ever collided with Earth, it could cause planet-wide devastation, so astronomers keep a careful watch on its movements using radar to track any changes in its trajectory. ✨
#asteroids⚡#hazards⚡#monitoring⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels