Что делать если нужно поставить какую-то 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
A study on men found that eating garlic made their body odor smell more pleasant, more attractive, and less intense. Researchers collected sweat samples and had others rate the smell.
Note: The study tested sweat, not their breath.🤪
🧄👃🧪
[Read more]
@googlefactss
#ScienceFacts#DidYouKnow#HumanBody#Research
If you have ideas or feedback contact us:
@Googlefactss_Feedback_bot
The human digestive system is about 7–9 meters (23–30 feet) long. The small intestine measures about 3–7 meters (10–23 feet), and the large intestine is about 1.5 meters (5 feet) long. Food typically takes 24 to 72 hours to travel from the mouth to the toilet. This time can differ depending on what you eat, how much water you drink, and how active you are.
🧠📏⏱️
[Read more 1]
[Read more 2]
@googlefactss
#HumanBody#DigestiveSystem#ScienceFacts#DidYouKnow
A brain freeze happens when something very cold touches the roof of the mouth or the back of the throat. This causes blood vessels in that area to quickly narrow and then widen again. This change activates a nerve that sends pain signals to the brain, which is why the pain is felt in the head. The sensation usually lasts only a few seconds to about a minute.
🧊🧠⚡
[Read more]
@googlefactss
#BrainFreeze#HumanBody#ScienceFacts#Health
If you have ideas or feedback contact us:
@Googlefactss_Feedback_bot
Babies are born with around 30,000 taste buds. Adults have about one-third of that number. This means babies can taste more flavors than grown-ups. As people get older, they lose many taste buds, which changes how they experience food. 👶🍎
[Source]
@googlefactss#TasteBuds#Babies#ScienceFacts
Psychopaths, often called ‘evil,’ lack empathy and guilt. They were once seen as untreatable. New studies show therapy like CBT and computer training can reduce violence and help them feel empathy. Treatment is limited but promising. 🧠💡
[Read more]
@googlefactss#Psychopathy#Therapy#MentalHealth#ScienceFacts
Women outperform men in recognizing all faces, with a particular advantage for female faces. 👩🦰👨🦱
They recognize both male and female faces better than men do. Men do not show this same bias toward their own gender.
[New Link1] [New Link2]
@googlefactss#Psychology#FaceRecognition#GenderDifferences#ScienceFacts
Ants don't have lungs. They breathe through tiny holes along the sides of their bodies called spiracles. These connect to a network of tubes (tracheae) that deliver oxygen directly to their tissues.
[Read more]
@googlefactss
#Ants#Biology#Entomology#ScienceFacts
People who eat the mushroom Lanmaoa asiatica raw or undercooked have reported seeing tiny human-like figures moving around them.
These are called lilliputian hallucinations.
Reports from people across different cultures and backgrounds describe similar details, including small figures walking on floors and furniture.
The effects can begin 12–24 hours after eating and may last 1–3 days.
Some cases are serious and require hospital care.
Don't try this yourself..
🍄😵💫🧚♀🦄🍄🟫
[Read more 1]
[Read more 2]
[Read more 3]
@googlefactss
#Mushrooms#ScienceFacts#Hallucinations#Nature#DidYouKnow
If you have ideas or feedback contact us:
@Googlefactss_Feedback_bot
15 December 1970, Venera-7 became the first spacecraft to land on Venus and send data back to Earth. Despite problems, it transmitted temperature information for 23 minutes after landing. The mission showed that Venus has extreme heat and pressure.
[Source]
@googlefactss
#Venera7🚀#Venus🌍#SpaceExploration#ScienceFacts
Serge Voronoff performed experiments transplanting testicle tissue from monkeys into men and boys to try to improve health and vitality. He also grafted testicle tissue onto female goats in his research. These practices were done in the early 1900s but later found to be ineffective and controversial.
🙈✂️⚽️⚽️
[Read more]
@googlefactss
#SergeVoronoff#MedicalHistory#Transplants#ScienceFacts
Pregnant women have one more organ than non pregnant women.
The placenta is a temporary organ that grows in the uterus during pregnancy. It connects the mother and baby through the umbilical cord. It gives the baby oxygen and nutrients and removes waste like carbon dioxide. It also makes hormones that help the pregnancy continue and lets helpful antibodies pass to protect the baby.
"Fun" fact:
After birth, the placenta leaves the body.
Some people keep it and even consume it..
🤰👶🍽
[Read more]
[Don't eat it]
#placenta#pregnancy#humanbody#sciencefacts#biology@googlefactss
Isaac Asimov was born on January 2, 1920. He wrote the Three Laws of Robotics:
1. Robots can't harm humans or let them be harmed.
2. Robots must follow human orders unless it breaks the first law.
3. Robots must protect themselves unless it breaks the first or second law.
🤖📜
[Read more]
@googlefactss
#IsaacAsimov#Robotics#ThreeLaws#ScienceFacts