Что делать если нужно поставить какую-то 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
🪐 NASA’s Psyche mission is sending a high-tech spacecraft to the asteroid 16 Psyche, testing a new electric propulsion system called Hall thrusters. Hall thrusters use electricity and magnetic fields to accelerate charged particles (ions) for thrust, offering a more efficient way to travel long distances—demonstrating key technology that could power spaceships to worlds like Ceres or the moons of Jupiter in the future. ✨
#spaceships⚡#propulsion⚡#asteroids⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 ESA’s Hera mission, launching soon to study asteroid Didymos and its moon Dimorphos, is bringing a new kind of space probe—one equipped with autonomous navigation, letting the spaceship guide itself during its close encounters. This technology, inspired by how insects use simple visual cues to avoid obstacles, could pave the way for future spaceships that explore places like Jupiter’s moon Europa or the rings of Saturn independently, relying less on commands from Earth and more on real-time decisions. ✨
#spaceships⚡#technology⚡#exploration⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The future of interstellar travel may rely on building spacecraft capable of withstanding long-duration journeys across vast distances like the 4.37 light-years to Alpha Centauri. NASA’s Starlight project is studying how powerful ground-based lasers could push small, ultra-light probes to a significant fraction of the speed of light—over 100 million kilometers per hour—enabling them to reach nearby star systems in just a few decades rather than millennia. ✨
#spaceships⚡#technology⚡#exploration⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 The Japanese spacecraft Hayabusa2 demonstrated a glimpse of future spaceship technology by visiting the asteroid Ryugu, collecting samples, and returning them to Earth in 2020. Its advanced ion propulsion system and autonomous navigation allowed it to land and lift off from the tiny asteroid's weak gravity—a feat that opens the door to more complex robotic missions to objects like Bennu and even farther out in the solar system. ✨
#spaceships⚡#exploration⚡#technology⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 NASA's Solar System Ambassador program highlights the rapid development of electric propulsion for future spaceships, like the ion engines used on the Dawn spacecraft. Ion engines work by shooting electrically charged atoms, called ions, out of the back of the spacecraft, allowing for extremely efficient travel to distant worlds such as the asteroid Vesta and the dwarf planet Ceres. ✨
#spaceships⚡#technology⚡#exploration⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
🪐 NASA has announced plans for its first nuclear-powered rocket in over 50 years, aiming to test an engine in space by 2027. This new technology, called nuclear thermal propulsion, could dramatically reduce travel time to Mars and distant worlds like Europa by heating hydrogen to generate powerful thrust—making human missions to the outer solar system more achievable than ever before. ✨
#spaceships⚡#technology⚡#Mars⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 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
🪐 Scientists studying the future of interstellar travel are exploring how hydrogen harvested from interstellar space—called "ramjet" propulsion—could one day fuel journeys to stars like Alpha Centauri, located over 4 light-years from Earth. A concept known as the Bussard Ramjet proposes using a huge electromagnetic field to collect hydrogen atoms as a spaceship speeds through space, fusing them for energy in the same way stars do, potentially enabling continuous acceleration across vast cosmic distances. ✨
#spaceships⚡#technology⚡#AlphaCentauri⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 NASA’s upcoming VERITAS mission will send a spaceship equipped with advanced synthetic aperture radar and infrared sensors to Venus, mapping the planet’s surface in detail never achieved before. VERITAS will peer through Venus’s thick clouds to unveil its volcanic terrain and tectonic features, opening a new frontier for robotic exploration in one of the solar system’s most extreme environments. ✨
#spaceships⚡#venus⚡#technology⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 NASA’s upcoming DAVINCI mission is set to test a new kind of spaceship technology as it descends through the thick atmosphere of Venus in the late 2020s. The spacecraft will use a combination of heat shielding and parachutes designed to survive the planet’s crushing pressure and scorching surface temperatures—over 460°C—pushing the limits of materials and engineering needed for future robotic explorers of extreme worlds like Venus and beyond. ✨
#spaceships⚡#technology⚡#Venus⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels
🪐 Scientists are researching how self-healing materials could revolutionize interstellar travel, allowing future spacecraft bound for distant stars like Proxima Centauri to repair themselves from cosmic dust impacts and radiation damage. These advanced materials are designed to sense and fix tiny cracks or holes automatically, greatly increasing the durability and safety of deep space missions as they travel through the harsh, unpredictable environment between the stars. ✨
#spaceships⚡#technology⚡#innovation⚡#nasa⚡#galaxy⚡#stars⚡#astronomy⚡#universe⚡#cosmos⚡#space
👉subscribe Universe Mysteries
👉more Channels