Что делать если нужно поставить какую-то 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
Water can boil and freeze simultaneously at its "triple point," a specific, low-pressure state (0.01°C at 611.657 pascals) where solid, liquid, and gas phases coexist in equilibrium. Under these precise vacuum conditions, water molecules with enough energy escape as vapor (boiling), while the rapid heat loss causes remaining molecules to freeze.
@googlefactss#physics
On Pioneer 11
In December 1974 Pioneer 11 skimmed within 27.000 miles of Jupiters southern polar region.
Observations in the infrared from Pioneer 10 a year earlier had already indicated that the planet was much brighter than would be the case had it merely been a planet reflecting light.
D.A. Allen noted that Jupiter appeared so bright that it must be radiating more energy than it could absorb from the Sun.
"When the long wavelength data are also included, we find that Jupiter radiates nearly three times the energy it receives." - D.A. Allen, Infrared: The New Astronomy (1975)
This discovery should have been an earthquake in astronomy, but they kept being stubborn.
With the right electrical input, Jupiter (the Sky Father) could light up in former glory.
#physics
@EuropeanTribalism
#PHYSICS
🫧"Mehrli maktab" da fizika fanini o'qitish, avvalambor, o'quvchilarni zamonaviy fizika yutuqlari bilan tanishtirishni, hamda o'quvchilar ongida tabiiy -ilmiy dunyoqarashni shakllantirishni taqozo qiladi.
🌊Fizika tabiatdagi hodisa va voqealarni hamda ularning qonuniyatlarini o'rganuvchi fandir.
"Mehrli maktab " da fizika fanini o'qitishda yangi shakl va uslublarini faol joriy etish ham maqsadga muvofiqdir.
🌈Shu maqsadda o'quv jarayonida zamonaviy AKTdan foydalanish samarali natija bermoqda. O'quv mashg'ulotlar davomida "Birligini top!", "Xotira mashqi", "Olimlar gulshani", "Kamalak ranglari", "Formula daraxti", "Kashfiyotlar shahri" metodlaridan foydalanib darslar tashkil etiladi.
Instagram
Facebook
Twitter
Thor still thunderous. (Current NASA footage.)
Any more proof needed that the nature of the universe is electrical?
Our ancient gods are still out there.
It's crucial to understand mythology to accept this fact.
#physics
@EuropeanTribalism
https://youtu.be/iJfw6lDlTuA?list=PL701CD168D02FF56F
关于理论物理学的入门级视频,The Theoretical Minimum 系列(理论物理的最低理解要求)。由 Leonard Susskind 授课,理论物理学家,弦理论(String theory)早期几个先驱之一,曾是一名水管工。
对于拓宽知识和丰富体验,纪录片和教学视频都很不错。这个视频系列对理论物理学的入门吸收和拓展也刚好。之前 HN 网站还看到推荐的一个理论物理的博客学习 How to become a GOOD Theoretical Physicist ,也可以关注。迷人的“闻道”之旅。#physics
On the mysterious handbags of the ancients
Although I do not agree with the Thunderbolts people in every detail, they have great ideas and explanations for a lot of things.
They recently released a video, explaining what the mysterious "Handbag of the Gods" might actually be. This handbag can be found all around the globe in ancient reliefs with no connecting culture.
In short: it is a representation of an extreme electrical discharge event, seen as titanic storm.
Watch the video! It also explains to some degree, why we see severe weather conditions and earthquakes.
#physics#mythology
https://www.youtube.com/watch?v=a8C2OdSbw84
On friar Georges Lemaitre
Friar Georges Lemaitre, a Belgian priest and astrophysicist, published a paper in 1927 in the Annals of the Scientific Society of Brussel that first presented the idea of an expanding cosmos. In 1931, Lemaitre proposed what later became known as the 🔗Big Bang theory of the origin of the universe.
The Catholic Church honoured Lemaitre's work: he was elected to the Pontificial Academy of Sciences (sic!) in 1936 and named prelate in 1960.
By contrast, in 1948, astronomers in the atheist Soviet Union were urged to condemn the Big Bang as a reactionary theory helping clericalism, a hostility shared by many scientists and philosophers until the 1960s.
Besides showing the compatibility of faith and science, the case of Lemaitre illustrates the way in which minds and cultures shaped by the belief that (the Abrahamic) God is a Trinity of reason and love have proved fruitful in perceiving order in the universe.
Moreover, it is arguable that belief in (the Abrahamic) God who is beyond creation has freed us to theorise about the causation and change of the cosmos as a whole, rather than simply accepting the totality of material reality as an eternal, unchanging given.
#physics#history
@EuropeanTribalism
On the celestial mechanics and the past of the Solar system
A follower of this channel pointed out a video I want to share with you. It contains a brief summary of how the mechanics of the Solar system work and explain on point what this channel tells you about mythology.
Please watch and share, this video solves everything you need to know:
https://www.youtube.com/watch?v=8RtGal_-KXU
#physics#mythology#history
@EuropeanTribalism
Mulugeta Bekele: the jailed and tortured scientist who kept #Ethiopian#physics alive
Mulugeta Bekele paid a heavy price for remaining in #Ethiopia in the 1970s and 1980s. While many other academics had fled their homeland to avoid being targeted by its military rulers, Mulugeta did not.
He stayed to teach #physics, almost single-handedly keeping it alive in the country. But Mulugeta was arrested and brutally tortured by members of the #Derg, Ethiopia’s ruling military junta. “I still have scars,” he says when we meet at his tiny, second-floor office at Addis Ababa University (AAU) in January 2026.
Gentle and softly spoken, Mulugeta, 79, is formally retired but still active as a research physicist. In 2012 his efforts led to him being awarded the Sakharov prize by the American Physical Society (APS) “for his tireless efforts in defence of human rights and freedom of expression and education....
https://physicsworld.com/a/mulugeta-bekele-the-jailed-and-tortured-scientist-who-kept-ethiopian-physics-alive/