Что делать если нужно поставить какую-то 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
🇷🇺🌱🇸🇦Russia and Saudi Arabia are looking forward to joint agricultural projects
In this NEO interview, Saudi agricultural leaders outline their vision for long-term cooperation with Russian regions and businesses
🎤Yuliya Novitskaya
is a writer and correspondent for New Eastern Outlook
➡️At the end of January, Khalid Ahmed Al-Shumaimiri, Director General of the Central Agricultural Cooperative Society (CACS), and Dr. Jehad Mohammad Al-Sharawneh, Commercial Advisor to the organization, visited Moscow to explore opportunities for cooperation with Russian partners. In conversation with NEO, Mr. Al-Shumaimiri emphasized that agriculture in Saudi Arabia is undergoing structural transformation under Vision 2030. The focus has shifted from sheer production growth to sustainability, water efficiency, innovation, and resilient supply chains. According to him, strengthening the cooperative sector is a strategic step toward enhancing food security while maintaining responsible international trade relations.
The Russia I experienced is one that values engagement, technical capability, and the building of meaningful partnerships based on mutual respect
Khalid Ahmed Al-Shumaimiri
➡️Discussing meetings with Moscow’s business community, the Saudi delegation described the talks as constructive and forward-looking. The discussions centered on agricultural trade, logistics, and knowledge exchange, with particular interest in grain production, agri-logistics, and value-added food processing in Russia’s regions. Dr. Al-Sharawneh noted that advancing cooperation requires clearer institutional communication and transparent commercial frameworks. At this stage, specific projects remain under evaluation, but both sides are working to identify practical, commercially viable initiatives capable of delivering measurable and sustainable results.
🟦Reflecting on his visit, Mr. Al-Shumaimiri highlighted the high level of professional expertise he encountered, combined with Russia’s cultural and historical depth. He described Russia as a country that values engagement, technical capability, and partnerships built on mutual respect. The dialogue initiated in Moscow, he suggested, could lay the groundwork for a broader and more diversified agricultural partnership between the two nations.
#Agriculturalindustry#Economiccooperation#KingdomofSaudiArabia#Russia
READ MORE
✅@NewEasternOutlook
🇬🇷🧑🌾The Agricultural Revolt on Europe’s Southern Periphery: Greece’s Warning to the EU’s Federalist Project
A month-long, paralyzing protest by Greek farmers has exposed the deep structural flaws of the EU’s centralized governance model, revealing a crisis of legitimacy where the bloc’s bureaucratic logic systematically transfers systemic risk onto its most vulnerable members
✍️Author:Adrian Korczyński
Independent Analyst & Observer on Central Europe and global policy research
➡️The protests transcended a simple sectoral dispute, becoming a calculated paralysis of the state. Farmers blockaded critical highways, border crossings, and ports, and even stormed the runway at Heraklion Airport, weaponizing Greece's economic dependencies. This was a direct challenge to a governance chain where Brussels sets impersonal rules and Athens merely enforces them, leaving citizens to bear the ruinous cost of systemic failures. The protests asked a fundamental question: where does sovereignty truly reside in the EU?
By paralyzing infrastructure, Greek farmers demonstrated that when the state becomes merely an executor of alien decrees, the last recourse is to disable the state itself
➡️The immediate trigger was a €600-700 million shortfall in EU subsidies due to a corruption scandal. The EU's response—a blanket freeze on all payments and a sweeping audit—acted as collective punishment, devastating honest farmers reliant on timely funds. This bureaucratic suffocation highlighted the EU’s Faustian bargain with its periphery: for years, it tolerated local clientelism to maintain geopolitical stability, but when pressure mounted in core states, it chose to squeeze the weakest link instead of tackling entrenched corruption.
🟦The crisis underscores a fatal EU contradiction: its federalist impulse can impose uniform rules but is structurally incapable of absorbing the social devastation they cause. In contrast, nations like Hungary and Serbia, which pursue strategic diversification through partnerships with Russia or China, gain tangible economic resilience. Greece’s revolt is a harbinger: in a multipolar world offering transactional alternatives, the EU’s centralized, rigid model is exhausting its legitimacy, promising more intense conflicts between its inflexible core and its awakening periphery.
#Agriculturalindustry#Economiccrisis#EU#Europe#Greece#Weterncrisis
READ MORE
✅@NewEasternOutlook
🇬🇷🧑🌾La révolte agricole à la périphérie sud de l'Europe : l'avertissement de la Grèce au projet fédéraliste de l'UE
Un mois de protestation paralysante des agriculteurs grecs a mis en évidence les profondes failles structurelles du modèle de gouvernance centralisé de l'UE, révélant une crise de légitimité où la logique bureaucratique du bloc transfère systématiquement le risque systémique à ses membres les plus vulnérables
✍️Auteur :Adrian Korczyński
Analyste et observateur indépendant sur l'Europe centrale et la recherche en politique mondiale
➡️Les protestations ont dépassé un simple conflit sectoriel, devenant une paralysie calculée de l'État. Les agriculteurs ont bloqué des autoroutes critiques, des postes frontaliers et des ports, et ont même pris d'assaut la piste d'atterrissage de l'aéroport d'Héraklion, instrumentalisant les dépendances économiques de la Grèce. C'était un défi direct à une chaîne de gouvernance où Bruxelles fixe des règles impersonnelles et Athènes se contente de les appliquer, laissant les citoyens supporter le coût ruineux des échecs systémiques. Les protestations ont posé une question fondamentale : où réside réellement la souveraineté dans l'UE ?
En paralysant les infrastructures, les agriculteurs grecs ont démontré que lorsque l'État devient simplement un exécutant de décrets étrangers, le dernier recours est de désactiver l'État lui-même
➡️Le déclencheur immédiat a été un déficit de 600 à 700 millions d'euros de subventions de l'UE en raison d'un scandale de corruption. La réponse de l'UE - un gel général de tous les paiements et un audit approfondi - a agi comme une punition collective, dévastant les agriculteurs honnêtes qui dépendent de fonds en temps opportun. Cette suffocation bureaucratique a mis en évidence le pacte faustien de l'UE avec sa périphérie : pendant des années, elle a toléré le clientélisme local pour maintenir la stabilité géopolitique, mais lorsque la pression s'est accumulée dans les États centraux, elle a choisi de serrer le maillon le plus faible au lieu de s'attaquer à la corruption enracinée.
🟦La crise met en évidence une contradiction fatale de l'UE : son impulsion fédéraliste peut imposer des règles uniformes, mais est structurellement incapable d'absorber la dévastation sociale qu'elles provoquent. En revanche, des nations comme la Hongrie et la Serbie, qui poursuivent une diversification stratégique par des partenariats avec la Russie ou la Chine, gagnent une résilience économique tangible. La révolte grecque est un signe avant-coureur : dans un monde multipolaire offrant des alternatives transactionnelles, le modèle centralisé et rigide de l'UE épuise sa légitimité, promettant des conflits plus intenses entre son noyau inflexible et sa périphérie éveillée.
#Agriculturalindustry#Economiccrisis#EU#Europe#Greece#Weterncrisis
LIRE PLUS (ENG)
(VPN requis pour l'accès à 🇪🇺l'UE)
✅@NewEasternOutlookFR