Что делать если нужно поставить какую-то 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
Con il nostro giro del mondo, ora voliamo in #Serbia.
🇺🇸Con l’elezione di Biden negli Usa, le politiche statunitensi sono destinate a cambiare. I loro effetti si spingeranno sino ai Balcani, intaccando anche lo strano equilibrismo che costituisce il tratto peculiare della nazione tradizionalmente considerata egemone nell’area: la Serbia.
🇷🇸Visto l’appoggio concesso a Trump per il suo disinteresse sulla questione aperta del Kosovo, il presidente serbo Aleksander Vučić – già costretto ad affrontare i movimenti interni che denunciano una torsione autoritaria – dovrebbe essere annoverato tra gli sconfitti.
📥Non è così facile in Serbia, dove la politica estera si basa su quattro pilastri: i rapporti con Usa, Ue, ma anche Cina e Russia. Mantenere buoni rapporti con una nazione così influente è prerogativa essenziale. Nonostante tutto, l’elezione di Biden rischia di minare questo equilibrio.
▶️vai all'articolo
🇷🇸#SerbiaМарш за семейные ценности в Белграде⚠️☝️
💬 Люди продолжают выходить на шествия в поддержку семейных ценностей, даже после победы над гей-парадом, который смогли отменить люди, показав свою решительность в этом вопросе.
🇷🇸#SerbiaСербские фермеры вышли на забастовку⚠️☝️
💬 Дороги, ведущие к правительственным учреждениям в Нови-Саде и Воеводине, перекрыты из-за повышения стоимости топлива.
💬 «Если вы не выполните наши требования, то мы заблокируем всю страну!»
‘This is like Hitler’s Kristallnacht when he killed about 90 people, and they want to kill much more.’
In an exclusive interview with RT Documentary, Emir Kusturica compared European politics to Hitler's actions. The director is sure it is impossible to cancel Russian culture. Moreover, he calls on his colleagues to open a new chapter of Russian history: ‘We must bring Dostoevsky to the planet, not only to Europe.’
Kusturica is the creator of the Kustendorf Film Festival. More than 500 films from all over the world have been selected for the festival this year. The Russian movie Clear Sky has been awarded the gold. Emir Kusturica is one of the subjects in our new documentary about Russia's friends in Europe, and there are many of them.
Will you be waiting for thepremiere?
#video#Serbia
Follow: https://t.me/rtdocumentary
Serbian Woodstock 🎺
#video#Serbia
Every year, thousands of revellers gather in a small Serbian town to dance their feet off, immerse themselves in Balkan brass music and feel like characters in a Kusturica movie. It’s the annual trumpet festival in Guca that runs for five days straight.
Brass bands come from all over Serbia to compete for the ‘Golden Trumpet’ trophy, make a little money and get noticed by industry leaders. The Guca festival was first held in 1961 and has since grown into Serbia’s biggest music event.
Brass bands are an essential part of every major event, including births, weddings and funerals. Find out more about the festival and see what it’s like to party in Serbia - https://youtu.be/WwP_AdfNERg
Follow: https://t.me/rtdocumentary
#Ungheria#Serbia
La diretta sulle elezioni ungheresi e serbe è disponibile su Spotify: https://sptfy.com/7XzX
Se vuoi supportare il nostro lavoro, offrici un caffè: https://ko-fi.com/ultimorapolitics
@UltimoraPolitics
#Serbia. Protestas denunciando fraude en las #elecciones.
https://www.euractiv.com/section/enlargement-neighbourhood/news/opposition-supporters-break-windows-at-belgrade-town-hall/
🇷🇸#Serbia – 🇭🇺#Hungary: Two backpacks containing what Serbian authorities described as “US-made plastic explosives” were discovered in Kanjiza, a few hundred meters from the TurkStream pipeline linking the town to the Hungarian border.
The devices, along with detonators, were found yesterday by the Serbian military and police near the gas infrastructure.
Serbian officials have said that they had prior intelligence that a “man with military training from the migrant community” was planning a diversion targeting the pipeline.
On the Hungarian side, PM Viktor Orbán convened an emergency defence council, calling it a planned sabotage and warning of threats to energy security ahead of the April 12 elections.
The incident has escalated into a political crisis in Hungary, with opposition figures suggesting a possible "false flag" in order to influence the upcoming elections.
No arrests have been made, as suspects, motive, and responsibility remain unknown.
(via Reuters & CNN)
🇭🇺⛽️🪖Parte de TurkStream será protegido por el Ejército húngaro
Fuerzas húngaras se encargarán de la proteccióndel tramo del gasoducto TurkStream en territorio del país, desde Serbia hasta Eslovaquia, declaró el canciller, Peter Szijjarto.
Cuatro países, Hungría, Serbia, Turquía y Rusia, acordaron tomar medidas decisivas para proteger el gasoducto, agregó.
Anteriormente, el presidente de Serbia, Aleksandar Vucic, informó durante una conversación telefónica con el primer ministro húngaro, Viktor Orban, sobre el hallazgo de una bomba a pocos cientos de metros del gasoducto entre Hungría y Serbia.
Según Szijjarto, el último intento de sabotaje "encaja bien en una serie" de acciones de Ucrania contra el suministro energético de Hungría.
Los informes preliminares de los servicios serbios apuntan a un inmigrante con formación militar como sospechoso en el incidente con bomba en Serbia.
📷 IA
#hungría#serbia#ucrania
———
Únete a la lucha por la verdad en
📱Telegram
📱 YouTube
🫥Odysee
📱X