Что делать если нужно поставить какую-то 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
#LetHerBloom
#GretaThunberg
❔What happens when a climate activist speaks out on a global conflict?
💬 Greta Thunberg has always been loud - for the planet, and for the people.
However when she spoke up about Palestine, the silence that followed was different…
On June 9, she boarded humanitarian flotilla the Madleen, planning to deliver aid to Gaza. Israeli forces intercepted the vessel in international waters, detaining and then deporting her by June 10 - after being held in an undisclosed location and pressured to sign documents admitting illegal entry.
‼️ She is back safe, but the reality remains:
Solidarity can come with heavy costs.
🌸 At Bloom, we believe speaking up and fighting is better than staying silent!
So let’s fight for justice and stop traditions of staying silent in unfair situations.
And again,
Let Her Bloom!
Greta Thunberg talks about her life
Staying grounded makes coming back to normal life easier, climate activist Greta Thunberg says, as she talks about her handling of fame.
#News#Reuters#GretaThunberg#lifestyle
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Some snippets from Greta’s interview after being deported by Israeli authorities. Continue fighting for Palestinians in Gaza, including those in wider Palestine who are unlawfully imprisoned, including over 400 children.
#Madleen#IOF#GretaThunberg#FreedomFlotilla
https://x.com/SavinoBalzano/status/1974887738919772654
Penso davvero che #AntonioTajani rappresenti uno dei punti più bassi della storia della diplomazia italiana.
Uno che va in televisione a dire che il diritto internazionale conta fino a un certo punto. Uno che parla di “abordaggi pacifici”. Uno che sottolinea come i nostri concittadini non siano stati trattati da #Israele come terroristi.
A parte il fatto che mente spudoratamente: da quanto emerge, le condizioni di detenzione sono state inaccettabili e, soprattutto, gli israeliani si sono accaniti sulle persone trattenute con azioni a dir poco intollerabili. Vale però la pena ricordare, ancora una volta, che i membri della #Flottilla non stavano commettendo alcuna azione illegale. Erano in acque internazionali (acque di tutti e di nessuno) e, soprattutto, del tutto disarmati. Per quanto ci riguarda, i nostri concittadini erano anche su imbarcazioni battenti bandiera italiana, dunque su territorio della Repubblica. La stessa Repubblica di cui, purtroppo (per quanto mi riguarda), #Tajani è ministro.
Ora mi rivolgo a tutti, anche agli amici di destra. Gli attivisti possono anche esservi antipatici (personalmente non ho mai nutrito alcuna simpatia per #GretaThunberg), ma non comprendere che tenere la gente in carcere illegalmente, affamarla e assetarla, costringerla a baciare la bandiera israeliana in una cella infestata dalle cimici, sia semplicemente barbaro, vi rende peggiori di chi più vi ripugna. Sia chiaro.
E qualcuno ha ancora il coraggio di parlare dell’unica democrazia del Medio Oriente? Ma con che faccia?
#BattitoriLiberi: dal lunedì al venerdì alle 17, su Radio Cusano
Greta grooves at Stockholm climate concert
Swedish climate activist Greta Thunberg surprised the crowd at the Climate Live concert in Stockholm by delivering a dance rather than a speech.
#News#Reuters#GretaThunberg#Stockholm#RickAstley
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
https://x.com/SavinoBalzano/status/1974887738919772654
Penso davvero che #AntonioTajani rappresenti uno dei punti più bassi della storia della diplomazia italiana.
Uno che va in televisione a dire che il diritto internazionale conta fino a un certo punto. Uno che parla di “abordaggi pacifici”. Uno che sottolinea come i nostri concittadini non siano stati trattati da #Israele come terroristi.
A parte il fatto che mente spudoratamente: da quanto emerge, le condizioni di detenzione sono state inaccettabili e, soprattutto, gli israeliani si sono accaniti sulle persone trattenute con azioni a dir poco intollerabili. Vale però la pena ricordare, ancora una volta, che i membri della #Flottilla non stavano commettendo alcuna azione illegale. Erano in acque internazionali (acque di tutti e di nessuno) e, soprattutto, del tutto disarmati. Per quanto ci riguarda, i nostri concittadini erano anche su imbarcazioni battenti bandiera italiana, dunque su territorio della Repubblica. La stessa Repubblica di cui, purtroppo (per quanto mi riguarda), #Tajani è ministro.
Ora mi rivolgo a tutti, anche agli amici di destra. Gli attivisti possono anche esservi antipatici (personalmente non ho mai nutrito alcuna simpatia per #GretaThunberg), ma non comprendere che tenere la gente in carcere illegalmente, affamarla e assetarla, costringerla a baciare la bandiera israeliana in una cella infestata dalle cimici, sia semplicemente barbaro, vi rende peggiori di chi più vi ripugna. Sia chiaro.
E qualcuno ha ancora il coraggio di parlare dell’unica democrazia del Medio Oriente? Ma con che faccia?
#BattitoriLiberi: dal lunedì al venerdì alle 17, su Radio Cusano
Thunberg expects 'meaningless' pledges at COP26
For activist Greta Thunberg, success at the upcoming U.N. climate conference would be possible if world leaders honestly admit that their action is not living up to their words.
#GretaThunberg#COP26#UNClimateConference#ClimateChange#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Macklemore endorses the Freedom Flotilla’s ‘Madleen’ on stage, playing a special video that Greta Thunberg recorded from the vessel. Keep all eyes on deck, and all eyes on Palestine.
#GretaThunberg#Macklemore#BreakIsraelsSiege#EndTheBlockade#StandWithGaza#FreePalestine
Listen to some of the Freedom Flotilla Coalition volunteers share why our nonviolent action is critical, just before they boarded the 'Madleen' in Catania. Keep track of our vessel and friends as they sail to Gaza via Marine Traffic or our website. Tag your Foreign Ministries to ensure that they safeguard the 'Madleen', and end their active participation in Israel's genocide and siege of Gaza.
#BreakIsraelsSiege#EndTheBlockade#Madleen#FreedomFlotilla#HuwaidaArraf#GretaThunberg#DrMo#RimaHassan#YasmineAcar#ThiagoAvila