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

Резултати

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

Пребарај: #euthieves

当前筛选 #euthieves清除筛选

🎙Russia's Foreign Minister Sergey Lavrov’s interview with RIA Novosti(November 9, 2025) Read in full (Telegraph) #RussiaUS#NewSTART ❓ Question: President of Russia Vladimir Putin announced that the Russian Federation is prepared to continue adhering to the restrictions established by New START for one additional year, starting February 5, 2026. Has there been any response from the United States? Did Moscow propose a meeting with Washington to discuss the post-New START period? If so, at what level? 💬Sergey Lavrov: The constructive initiative put forward by President Vladimir Putin in the post-New START context speaks for itself. It contains no hidden agenda and is perfectly clear for understanding. Its practical implementation would not require any special additional efforts. <...> The only thing required is reciprocity from the United States: we will voluntarily adhere to the restrictions only if, and precisely for as long as, the other side does the same. <...> So far, there has been no substantive response from Washington. We have been informed through diplomatic channels that “the issue is under consideration.” We have no intention of keeping persuading anyone. We believe that our step serves the interests of both parties and the entire international community. 👉 We are ready for any development of events, while hoping for a positive outcome. #Ukraine#RussiaUS ❓ Question: What is currently the main stumbling block in the negotiations with the United States on a settlement around Ukraine? Where is Russia ready to make concessions and where is it not? 💬Sergey Lavrov: <...> We are currently awaiting confirmation from the United States that the Anchorage agreements remain in effect. I would emphasise that, despite their essentially compromise nature, we have not abandoned – and do not intend to abandon – the points that are fundamental for us. ❗️ No one disputes the territorial integrity of the Russian Federation or the choice made by the residents of Crimea, Donbass, and Novorossiya, who made their historic decision to reunite with their homeland through the referendums in 2014 and 2022. We likewise do not forget the need to eliminate the root causes of the conflict. #EUthieves ❓ Question: What will be Russia’s response if the frozen assets of the Russian Federation are directed to support Kiev? 💬Sergey Lavrov: <...> Such actions amount to outright deception and theft. It seems that the long-dormant instincts of colonialists and pirates have reawakened among Europeans. No matter how the scheme for seizing Russian funds is presented, there is no lawful way to carry it out. The confiscation of our gold and foreign currency reserves will not save the Europe’s protégés in Kiev <...> Russia will respond to any predatory actions appropriately, in accordance with the principle of reciprocity, our national interests, and the need to compensate for the damage caused to us. We hope that Brussels and other Western capitals will still come to their senses and abandon this ill-advised venture. #RussiaUS ❓ Question: When and where could a meeting between the Russian and American delegations on mutual “irritants” take place? What about your meeting with US Secretary of State Marco Rubio? When and where might it be held? 💬Sergey Lavrov: There are indeed many irritants in Russia-US relations, most of them inherited from the previous US administration. It will take considerable time to clear up this mess. <...> From our perspective, it is important that this dialogue should not be limited solely to embassy-related issues. We consider it essential to address broader questions, including the restoration of direct flights and the return of Russian diplomatic property. <...> Secretary of State Marco Rubio and I share an understanding that maintaining regular communication is essential, both for discussing the Ukrainian issue and for advancing the broader bilateral agenda. We remain in contact by phone and are prepared to hold in-person meetings.