TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #210 · 3 фев.

Что делать если нужно поставить какую-то 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

Резултати

Пронајдени 2 слични објави

Пребарај: #internationalaffairs

当前筛选 #internationalaffairs清除筛选

🎙 Russia's Foreign Minister Sergey Lavrov’s interview with Marina Kim for the New World project (Moscow, November 14, 2024) Key talking points: #InternationalAffairs • Our main task now is to achieve all the goals formulated by President Vladimir Putin. You are aware of the West’s expectations. They are speculating about stopping the hostilities at a certain line and coordinating a truce, so that 10 years from now they will decide who Crimea and Donbass belong to. This is coffee cup reading. I won’t engage in it. We have our tasks, and we will fulfil them. • Our job is to assert and promote Russia’s interests in keeping with its Constitution as well as the objectives defined by President Vladimir Putin. This goes beyond Ukraine and applies to Russia’s Foreign Policy Concept in general. #USA • Washington can’t allow Russia to prove that it is a strong player and undermine the West’s reputation. They don’t care about Ukraine. They only care about their reputation. They decided that Ukraine should have a government they like and didn’t expect anyone to protest. Russia? It’s a big country but it must be brought down a peg. That is what this is about rather than the future of the Ukrainian people. They don’t care about people. • Sanctions have been imposed on over half of the world’s countries, even if they are not as drastic as those that have been adopted against Russia, the Democratic People’s Republic of Korea, Iran and Venezuela. The real reason behind the West’s current rage is that China is rapidly and confidently surging ahead of the United States. • We can see through what the Americans want. Sitting somewhere overseas, they believe that they are beyond the reach, while leaving it to Europe to overcome the challenges they face in terms of encouraging and arming Ukraine to fight Russia, as well as footing the bill for the Middle East tragedy. #Eurasia4You • God gave us one continent, and we share it. This continent possesses immense and, in fact, the biggest natural resources, while several millennia-old civilisations inhabit it. Failing to benefit from these competitive advantages would be a mistake. This is what the idea of building a Greater Eurasian Partnership is all about, and the EAEU, SCO and ASEAN have already taken the first steps in this direction. We are establishing ties and promoting dialogue. If we succeed in fulfilling the plans we have, the Greater Eurasian Partnership will offer a solid foundation and serve as an economic and transport backbone for what President Vladimir Putin called a new Eurasian security architecture. • There is a clear understanding that the Eurasian security architecture, just like the Greater Eurasian Partnership, must be open to all countries and continents, including Eurasia’s western part, even if so far the latter has been trying, as if by inertia, to ensure its interests within a Euro-Atlantic security concept instead of opting for the Eurasian framework, which would be natural and reasonable, considering the geography factor. This is their way of saying that they do not intend to do anything without the United States. #BRICS 🌐 BRICS is about the new world order that is based on the main principle of the UN Charter – the sovereign equality of states. • BRICS has no intention of dividing the world. It wants to bring together countries that desire closer relations so that they can live on the land they got from God and their ancestors just as they used to, as great civilisations. #Africa 🌍 Decolonisation has taken place, in a broad sense. But being able to actually manage one’s freedom and resources is a different story. This is where neo-colonialism comes to the fore. • The First Ministerial Conference of the Russia-Africa Partnership Forum in Sochi, and the Russia-Africa Summit in St Petersburg in 2023 clearly put into perspective the trends that could be called Africa’s second awakening.