Что делать если нужно поставить какую-то 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 phenomenon of synesthesia allows some people to experience a blending of senses—like seeing colors when hearing music or tasting flavors from words. This rare trait reveals how flexible and interconnected the human brain’s sensory pathways can be. ✨
#neuroscience⚡#consciousness⚡#perception
👉subscribe Interesting Planet
🌎 Marathon runners often report “time expansion,” where minutes can feel much longer during intense effort. This phenomenon is linked to changes in dopamine levels in the brain, affecting how we sense passing seconds. Scientists have tracked measurable shifts in perceived time during both high physical exertion and tasks demanding intense attention. ✨
#time⚡#neuroscience⚡#perception
👉subscribe Interesting Planet
👉more Channels
🌎 Time can seem to slow down or speed up based on emotional state. Studies show heightened fear, such as during accidents, leads people to recall more detail, but does not actually slow objective time. Experiments reveal our brain may stretch memory to make intense events feel longer, a phenomenon called time dilation. ✨
#neuroscience⚡#perception⚡#psychology
👉subscribe Interesting Planet
👉more Channels
🌎 The phenomenon of "temporal binding" describes how the brain knits together events that happen closely in time, making them feel like a single, unified event. Studies show people often judge actions and their effects as happening closer together than they really are, revealing how the human mind shapes our perception of time’s flow. ✨
#neuroscience⚡#psychology⚡#perception
👉subscribe Interesting Planet
👉more Channels
🌎 Time perception can be dramatically altered by body temperature, with research showing people exposed to cold environments often overestimate how much time has passed. This effect is linked to changes in the brain’s internal clock, and studies found that participants in cold water estimated intervals were about 20% longer than in neutral conditions. ✨
#neuroscience⚡#psychology⚡#perception
👉subscribe Interesting Planet
👉more Channels
🌎 Time can feel stretchy in our minds! In moments of stress or fear, your brain’s perception of time slows down—an effect called “time dilation.” The brain records more details during intense experiences, making events seem to last longer in memory. That’s why scary or thrilling moments feel like they stretch on forever, even though the real clock keeps ticking at its usual pace. ✨
#neuroscience⚡#psychology⚡#perception
👉subscribe Interesting Planet
🌎 Your sense of time can shift dramatically—scientists call these “time anomalies.” Strong emotions or new environments can make minutes feel like hours, or hours like seconds. This happens because your brain judges time based on how much information it’s processing, not by the clock. Moments packed with novelty or excitement seem longer, while routine days fly by unnoticed. ✨
#psychology⚡#perception⚡#brain
👉subscribe Interesting Planet
🌎 The phenomenon known as synesthesia causes some people to involuntarily link senses, such as perceiving numbers or letters as specific colors. Brain scans show increased cross-activity between sensory regions in synesthetes, and the trait is estimated to occur in about 4% of people. ✨
#neuroscience⚡#perception⚡#senses
👉subscribe Interesting Planet
👉more Channels
🌎 Our sense of time is shaped by specialized brain regions, including the cerebellum, basal ganglia, and the right supplementary motor area. Research using brain imaging and patient studies shows damage to these areas can create time perception anomalies—such as feeling time stretch, shrink, or fragment unexpectedly. The cerebellum, once thought only to control movement, plays a key role in accurately judging short time intervals. ✨
#neuroscience⚡#perception⚡#anomalies
👉subscribe Interesting Planet
👉more Channels
🌎 In rare cases, time perception can be distorted by neurological conditions such as temporal lobe epilepsy or brain injuries. People may report "time slowing down," déjà vu, or missing chunks of experience. Some individuals with temporal lobe seizures even describe feeling like time has stopped completely. ✨
#neuroscience⚡#perception⚡#anomalies
👉subscribe Interesting Planet
🌎 Your brain uses a region called the "suprachiasmatic nucleus" as its master clock, syncing your sense of time to light and dark cycles. Disruptions—like jet lag or shift work—can make time feel faster or slower, and this clock influences sleep, alertness, and body temperature rhythms. ✨
#perception⚡#neuroscience⚡#circadian
👉subscribe Interesting Planet
👉more Channels
🌎 Certain types of migraine can cause "time dilation" or "time compression"—making minutes feel like hours or vice versa. Research links these time perception anomalies to abnormal brain activity in areas responsible for processing time and sensory input. Migraine auras affecting time sense have been documented in up to 15% of patients. ✨
#migraine⚡#neuroscience⚡#perception
👉subscribe Interesting Planet
👉more Channels