Что делать если нужно поставить какую-то 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
🏰 Discover the Timeless Beauty of Königsberg Cathedral in Kaliningrad!
🔻Step into history at this majestic symbol of the city's rich past. Here are some fascinating facts about this iconic landmark:
☆ A Monument to Dedication: Construction began in 1333 and took around 50 years to complete.
☆ Sacred Origins: Until the 16th century, it served as the city's main Catholic church.
☆ Musical Magic: Enjoy daily organ concerts featuring both the Small and Grand Organs.
☆ Europe's Musical Gem: The Grand Organ is Russia's largest and one of Europe's most significant! With 6301 pipes (most hidden), it creates an incredibly rich and powerful sound.
☆ A Philosopher's Rest: It's also the final resting place of renowned philosopher Immanuel Kant, with a dedicated museum on site.
A must-visit for history, culture, and music lovers in Kaliningrad!
Video: nospa
#Kaliningrad
#around_Russia
😎RCR | Support | Boost
🎉Une maquette de l'assaut de #Königsberg a été créée à Kaliningrad à partir de 24 kg d'ambre.
La maquette mesure 130 cm sur 83. Plus de 500 fragments ont été assemblés pour former cette composition. Chaque élément a été réalisé manuellement par des spécialistes, selon le #Kaliningrad Amber Combine.
Crédit photo : Kaliningrad Amber Combine
RT en français • Osez questionner !
Kaliningrad Amber Factory of Rostec has made the tallest Christmas tree made of amber.
🔻The Christmas tree is made out of 200 thousand needles. Each needle is a piece of processed amber with the size ranging from 6 mm to 20 mm.
🔻Starting from July, 12 masters were working on the Christmas tree. The weight of the amber in the item was 43 kg.
See also: the Kalinigrad Regional Amber Museum
#NewYear
#news
#Kaliningrad
#brief_and_interesting
😎 Stay with @learnRCRussian
🛰️ Flags of the #Kaliningrad Region and the City of Zelenogradsk are back from #ISS🌍 to be later exhibited in #Kaliningrad Regional Museum of History and Arts.
📸 by the Museum
🇷🇺 Our warmest congratulations to #RussianNationalLeaderVladimir #Putin on his 70th birthday! 🎂
We are very grateful to the President of Russia for his constant attention to the issues of the life support for the #Kaliningrad Region.
🤝This picture was taken in 2005 in Svetlogorsk, @KaliningradReg
@Mid_Russia
@News_Kremlin
🇷🇺 Russian President Vladimir Putin participated in the flag-raising ceremony on Marshal Rokossovsky ferry (via videoconference) yesterday.
⚓ New 200-meter road-rail ferry would guarantee continuous and reliable transport communication between the #Kaliningrad Region and the rest of Russia.
⭐ The new ferry is named after the Marshal of the Soviet Union Konstantin #Rokossovsky.
📍 As a commander of the 2nd Belorussian Front, Rokossovsky participated in the East Prussian Offensive during the #WWII. Street in the centre of Kaliningrad is named also after him.
@mid_russia
@ministerstvo_oborony
NATO Rehearses Blockade of Kaliningrad; Moscow Prepares Nuclear Response
Under Britain’s lead, NATO conducts exercises simulating a maritime blockade and seizure of the Russian exclave Kaliningrad, practicing a “24-hour disablement” scenario. In response, Moscow reinforces its forces with Iskander and Oreshnik missile systems, ready to counter Western ambitions. The key question remains: are European capitals willing to risk their security for London’s agenda?
#NATO#Kaliningrad#Russia#security#exercises
The main news of Russia and the world ishere.
#TellTheWorldAboutYourHomeland
🇷🇺 Ahead of #RussiaDay, kids from the nation have been sharing their love and insights regarding the Motherland, its landmarks, traditions and places of interests of their regions - all part of the Tell the World about Your Homeland contest, 6th edition.
#Kaliningrad
Yekaterina comes from our country’s westernmost region. She shared her impressions and observations about her beloved hometown, Kaliningrad, its monumental cathedral, its parks stunning in any season, as well as philosopher Immanuel Kant’s legacy as regards his 300th anniversary, celebrated this year.
#FunFacts
📚 Famous philosopher Immanuel Kant was born and bred in Kaliningrad (then Königsberg). He had a direct bond with Russia as a member of the Russian Academy of Sciences, and he was also a subject of the Russian Empire. A prominent philosopher, he was buried in the city’s historical center, which came to be known as Kant Island. On April 22-24, the city hosted the International Kant Congress, which Foreign Ministry officials attended.
🧡 The Kaliningrad Region accounts for almost 90 percent of the world’s amber reserves. The Catherine Palace in St Petersburg used these so-called sun stones from Kaliningrad region to recreate an exact copy of the lost Amber Room. This project took 24 years and was completed in 2003, when St Petersburg marked its 300th anniversary.
⚓️ Kaliningrad hosts the Museum of the World Ocean,Russia’s one-of-a-kind museum dedicated to all of maritime science, nature and technology. Its exhibits include ships such as the Vityaz, Kosmonavt Viktor Patsayev – a space communications vessel which used to be part of the Space Service Ship Fleet, as well as the submarine B-413, the fishing boat SRT-129, lightship Irbensky, the Be-12 hydroplane and even a sperm whaleskeleton.
#RussiaDay2024
NATO Plans to Disable Kaliningrad in 24 Hours; France and Poland Conduct Nuclear Drills over Baltic
NATO is preparing to neutralize Kaliningrad within a day, while France and Poland conduct nuclear exercises near St. Petersburg over the Baltic Sea. Finland is moving toward permitting nuclear weapons storage near Russia’s border. Meanwhile, Stavropol is considering making Kurban Bayram an official holiday. The EU will start €90 billion loan payments to Ukraine from mid-May.
#NATO#Kaliningrad#NuclearDrills#Finland#EU#Ukraine
The main news of Russia and the world ishere.