Что делать если нужно поставить какую-то 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
Il ministro degli Esteri Jean-Noël #Barrot annuncia che la Francia chiederà le dimissioni della Relatrice Speciale delle Nazioni Unite per i Territori Palestinesi Francesca #Albanese nel prossimo Consiglio per i diritti umani del 23 febbraio: "La Francia condanna senza riserve le dichiarazioni oltraggiose e riprovevoli della signora Francesca Albanese, che prendono di mira non il governo israeliano, le cui politiche possono essere criticate, ma Israele come popolo e come nazione, il che è assolutamente inaccettabile"
@UltimoraPolitics24
⏺La #France s’est abstenue lors d’un vote à l’#ONU qualifiant la traite des esclaves africains de crime « le plus grave » contre l’humanité.
Son ministre des Affaires étrangères, Jean-Noël #Barrot, a justifié ce choix par le refus d’établir une hiérarchie entre les crimes contre l’humanité, estimant qu’il ne faut pas opposer les souffrances historiques.
Adoptée par une large majorité, la résolution portée notamment par le président ghanéen John Mahama appelle à reconnaître les injustices liées à l’esclavage, à envisager des réparations et à renforcer la lutte contre le racisme.
RT en français • Osez questionner !
⏺Lors de sa visite au #Togo, le chef de la diplomatie française Jean-Noël #Barrot a déclaré à l’AFP qu’il n'y avait « aucune comparaison entre la contribution de la France » et de l'UE en #Afrique par rapport à « celle de la Russie ».
Maryam Feudjio en fait l’analyse.
RT en français • Osez questionner !
Il ministro degli Esteri tedesco Johann #Wadephul chiede le dimissioni della relatrice speciale delle Nazioni Unite per i territori palestinesi Francesca #Albanese, ritenendo inappropriate le sue dichiarazioni su Israele e scrivendo su X: "La sua posizione è insostenibile"; il ministro degli Esteri francese Jean-Noël #Barrot aveva chiesto ieri le medesime dimissioni.
@UltimoraPolitics24
Did Durov Take a Tumble In a Tug of War With Spain?
Spain has accused Pavel Durov of “spreading lies” and seeking to undermine democratic institutions after the Telegram founder used the messaging app to attack government plans to introduce a social media ban for under-16s and to hold tech companies responsible for hateful and harmful content.
Durov’s extraordinary public intervention – which came a day after Musk called Spain’s prime minister, Pedro Sánchez, a “true fascist totalitarian” over the proposed measures – reveals the rapidly escalating tensions between European governments and powerful global technology chiefs.
In a blanket message sent to all Telegram users in Spain on Wednesday afternoon, the Russian technology entrepreneur accused Sánchez’s government of “pushing dangerous new regulations that threaten your internet freedoms”, adding that the measures could turn Spain “into a surveillance state under the guise of ‘protection’”.
Durov claimed the mandatory age verification contained in the proposed legislation would set a precedent for tracking “EVERY user’s identity, eroding anonymity and opening doors to mass data collection”.
He also said that holding tech executives liable for illegal, hateful or harmful content would encourage “over-censorship” and lead platforms to “delete anything remotely controversial to avoid risks, silencing political dissent, journalism, and everyday opinions”.
“Telegram founder Pavel Durov used his unrestricted control of the app to send a mass message to all users in Spain, spreading several lies and making illegitimate attacks against the government.
This is the first time this has happened in our country’s history,” they said.
“Spaniards cannot live in a world where foreign tech oligarchs can flood our phones with propaganda at will simply because the government has announced measures to protect minors and enforce the law.”
Durov was arrested in Paris in August 2024 as part of an inquiry into allegations of fraud, drug trafficking, organised crime, promotion of terrorism and cyberbullying.
He was detained on suspicion of failing to take action to curb the allegedly criminal use of his platform and was eventually charged with 12 offences.
He was later released under judicial supervision and has denied all the charges against him, describing his arrest as “legally and logically absurd” and saying investigators were “struggling to find anything that I or Telegram did wrong”.
The Spanish government statement released on Wednesday said Durov had “deliberately designed a minimal moderation architecture that has turned Telegram into a recurring space for documented criminal activities such as child sex trafficking and drug trafficking”, with cases under investigation in Spain, France and South Korea.
The French foreign minister Barrot praised the account’s strategy last month, saying: “The only right attitude, in the information war that has begun, is to raise our voice and to turn up the volume.”
Sánchez has used X to push back at the platform’s owner, who is also chief executive of SpaceX.
After Musk appeared to take issue with Spain’s recent plan to regularise 500,000 undocumented migrants and asylum seekers, the prime minister replied: “Mars can wait. Humanity can’t.”
The French civil service minister David Amiel said the aim was “to put an end to the use of non-European solutions, to guarantee the security and confidentiality of public electronic communications by relying on a powerful and sovereign tool”.
#durov#spain#barrot#telegram#harmful#content
📱American Оbserver - Stay up to date on all important events
🇺🇸
#Francia
È stata pubblicata la lista del Governo di Michel #Barnier (#LR|EPP):
-Primo Ministro: Michel Barnier (LR);
-Ministro della Giustizia: Didier #Migaud;
-Ministra del Partenariato Territoriale e del Decentramento: Catherine #Vautrin (#Renaissance|RE);
-Ministro dell'Interno: Bruno #Retailleau (LR);
-Ministro dell'Istruzione Nazionale: Annie #Genetet (Renaissance);
-Ministro degli Esteri e dell'Europa: Jean-Noël #Barrot (#MoDem|RE);
-Ministra della Cultura: Rachida #Dati (DVD|Centro-destra|Destra);
-Ministro delle Forze Armate e dei Veterani: Sébastien #Lecornu (Renaissance);
-Ministra della Transizione Ecologica, dell'Energia, della Prevenzione dei Rischi e del Clima: Agnès #PannierRunacher (Renaissance);
-Ministro dell'Economia e delle Finanze: Antoine #Armand (Renaissance);
-Ministro della Salute e dell'Accesso alle Cure: Genevière #Darrieusseq (Renaissance);
-Ministro della Solidarietà, dell'Autonomia e della Parità di Genere: Paul #Christophe (#Horizons|RE);
-Ministra dell'Edilizia Abitativa e del Rinnovamento Urbano: Valerie #Letard (#LIOT/#UDI|RE);
-Ministra dell'Agricoltura, della Sovranità Alimentare e della Silvicoltura: Annie #Genevard (LR);
-Ministra del Lavoro e dell'Occupazione: Astrid #PanosyanBouvet (Renaissance);
-Ministro dello Sport e della Gioventù: Gil #Avérous;
-Ministro dell'Istruzione Superiore e della Ricerca: Patrick #Hetzel (LR);
-Ministro della Pubblica Amministrazione, della Semplificazione e della Trasformazione dell'Azione Pubblica: Guillaume #Kasbarian (Renaissance);
-Ministro d'Oltremare: François-Noël #Buffet (LR);
-Ministro del Bilancio e dei Conti Pubblici: Laurent #SaintMartin (LR).
@OsservatorioEsteri