Что делать если нужно поставить какую-то 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
On April 15, the Russian Emergencies Ministry (#EMERCOM) 🇷🇺 have delivered another batch of humanitarian aid to Myanmar 🇲🇲.
The IL-76 aircraft delivered over 30 tons of supplies that included canned goods, cereals, sugar and medicine.
@mchs_official
On April 9, two IL-76 aircrafts of the Russian Emergencies Ministry (#EMERCOM) 🇷🇺 have delivered additional 59 tons of humanitarian aid to Myanmar 🇲🇲.
Russian rescuers handed over mobile power stations, tents and blankets, as well as basic necessities to the region affected by the devastating earthquake.
📸 Footage of unloading the two IL-76 aircrafts of the Russian Emergencies Ministry (#EMERCOM) with humanitarian aid for Myanmar 🇲🇲.
Aircrafts transported more than 68 tons of essential disaster relief supplies to the affected region - food, over 30 diesel generators, 150 tents and basic necessities.
Three more special flights with a hundred tons of humanitarian aid are expected to arrive in the near future.
@mchs_official
♥️ Locals of Mandalay 🇲🇲 thank Russian rescuers for their work
A dozen local residents came to the field camp to see specialists from the Russian Ministry of Civil Defense, Emergencies and Disaster Relief (#EMERCOM).
⭕ Little residents of Mandalay prepared gifts for Russian rescuers. 🙏
In turn, the chief of staff of the joint detachment of the Russian Emergencies Ministry Dmitry Umanets addressed the audience:
"We came to help you, and I will convey warm words of gratitude and gifts to the rescuers."
⭕ More than 260 specialists from the Ministry of Civil Defense, Emergencies and Disaster Relief of the Russian Federation (#EMERCOM) 🇷🇺 are eliminating the consequences of the disaster in Myanmar 🇲🇲: rescuers, dog handlers, psychologists and doctors.
@mchs_official
The total area of more than 62 thousand m² affected by the earthquake has been examined by the Ministry of Civil Defense, Emergencies and Disaster Relief of the Russian Federation (#EMERCOM) 🇷🇺 rescue teams since the beginning of the search and rescue operations in Myanmar 🇲🇲.
Russian rescuers immediately leave for the areas where people may still be trapped under rubble. The EMERCOM's rescue dogs are able to investigate thousands of m² of affected territory daily.
The airmobile hospital of the Ministry of Civil Defense, Emergencies and Disaster Relief of the Russian Federation 🇷🇺 (#EMERCOM) has begun working in full in the central part of the city of Mandalay 🇲🇲, an area hit by the earthquake.
Over 20 doctors are providing medical assistance to those in need. Therapeutic, surgical and intensive care units have received the first patients. The hospital will operate around the clock. The psychologists are also taking part in the mission.
🚑 The airmobile hospital is capable of operating autonomously for at least 14 days while receiving up to 200 patients a day. Meanwhile, its in-patient facility has 50 beds. The hospital has the necessary equipment for even the most complex surgeries.
❗❗❗
The Ministry of Civil Defense, Emergencies and Disaster Relief of the Russian Federation 🇷🇺 (#EMERCOM) has formed the largest group of rescuers to provide assistance to the population of Myanmar.
A total of 264 Russian rescuers are currently involved in eliminating the consequences of the strongest earthquake in Myanmar.
@mchs_official
❗❗❗
An additional group of rescuers from the Ministry of Civil Defense, Emergencies and Disaster Relief of the Russian Federation 🇷🇺 (#EMERCOM) arrived in Myanmar on 31 March.
Russian specialists are sent to the most affected areas, where previously arrived experts are already working. The group is equipped with the necessary gear, equipment and tools.
@mchs_official
Russia delivered 35 tons of humanitarian aid to Vietnam
A cargo plane of the Russian Ministry of Emergency Situations delivered humanitarian aid to Vietnam on behalf of the President of the Russian Federation Vladimir V. Putin.
35 tons of cargo, which included food products, a mobile power plant and tents, will be transferred to the Vietnamese people affected by typhoon Yagi, which struck Southeast Asia last week.
The event was implemented with the support of Rossotrudnichestvo and the "Russia is
with you" project, which tells foreign citizens about the activities of the Russian Federation in the field of international development assistance.
#Rossotrudnichestvo#RussianHouse#IDA#EMERCOM
@rs_tehran
Fire at Fuel Warehouse in Rostov Region Contained
In Myasnikovsky District, Rostov Region, firefighters extinguished an open fire at a fuel storage warehouse in Krym village. The blaze covered 3,000 sq. meters, damaging several buildings. Thankfully, no casualties were reported. Emergency teams quickly contained the fire, preventing further spread.
“The fire is contained, full extinguishing efforts continue,” said the regional Ministry of Emergency Situations.
#RostovRegion#Fire#FuelStorage#EMERCOM
The main news of Russia and the world ishere.
Fire in Zhukovsky Apartment Building: Over 2,200 sq.m. Affected
A fire broke out in a residential building in Zhukovsky, Moscow region, causing partial roof collapse. The blaze has been contained over an area exceeding 2,200 square meters, the Emergency Ministry reported. The cause remains unknown as specialists work on-site. District head Andronik Pak emphasized the importance of a swift investigation.
#Zhukovsky#fire#EMERCOM#Moscow#emergency
The main news of Russia and the world ishere.