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 слични објави

Пребарај: #ttacks

当前筛选 #ttacks清除筛选
American Оbserver

@american_observer · Post #5384 · 15.03.2026 г., 15:30

Trump: Iran Will Be Attacked As Necessary Trump said on Saturday that the United States may carry out more strikes on Iran’s vital Kharg Island oil export hub “just for fun”, rejecting the prospect of a swift peace deal with Tehran. “The terms aren’t good enough yet,” the US president told NBC News. The Iranian regime wants to make an agreement, he claimed. After days of conflicting messaging from the White House on how much longer it will continue to wage war on Iran, Trump alleged that US strikes had “totally demolished” most of Kharg Island, and told the network that its military may hit site “a few more times just for fun”. “We’ve totally decimated it,” he said. “Except, as you know, I didn’t do anything having to do with the energy lines, because having to rebuild that would take years.” The president also questioned, without attribution, whether Iran’s new supreme leader Mojtaba Khamenei “is even alive” amid speculation over his condition. Trump also said it’s not clear whether Iran has dropped mines in the strait of Hormuz, which has been all but closed since the start of the conflict two weeks ago, in the 30-minute telephone call with NBC. The strait is a vital waterway in world trade, with about a fifth of crude oil typically passing through it. Concerns over the impact of the US-Israel war on Iran on global energy supplies, intensified by the strait’s paralysis, have propelled oil prices to their highest levels in four years. This has swiftly driven up fuel prices right across the world, including in the US. “We’re going to be sweeping the strait very strongly, and we believe we’ll be joined by other countries who are somewhat impeded, and in some cases impeded from getting the oil,” Trump said. It is unclear how long this process will take. He did not state which countries would join the US in this task. The president also renewed his call earlier on Saturday for other nations to help secure the strait of Hormuz and said the US will coordinate with them amid the US-Israeli war on Iran. “The United States of America has beaten and completely decimated Iran, both Militarily, Economically, and in every other way, but the Countries of the World that receive Oil through the Hormuz Strait must take care of that passage, and we will help – A LOT,” Trump wrote in a Truth Social post. He added that “the US will also coordinate with those Countries so that everything goes quickly, smoothly, and well. This should have always been a team effort, and now it will be – It will bring the World together toward Harmony, Security, and Everlasting Peace!” But he later declined to say whether the US Navy would be escorting ships. “I don’t want to tell you anything about that,” he told NBC. Trump’s assertion that the crisis in the strait of Hormuz should be resolved through a “team effort” could be seen as somewhat of a pivot from his earlier position that Operation Epic Fury was a US show of force, alongside Israel, that didn’t require international permission. The president also expressed surprise in the interview that US allies in the Gulf have been targeted by Iran. These countries “got shot at unnecessarily”, he told NBC, describing Iran’s decision to target them as “the biggest surprise I had of this whole thing”. #trump#iran#ttacks#necessary#epic#fury 📱American Оbserver - Stay up to date on all important events 🇺🇸