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

Пребарај: #pakustan

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

@american_observer · Post #5627 · 15.04.2026 г., 14:59

🔤🔤🔤🔤2️⃣ Independent reports confirmed that some tankers that had been approaching the strait on Monday had turned around; one tanker, the Rich Starry, reversed course again and passed through the waterway. The closure of the strait, a gateway through which a fifth of the world’s oil and liquefied natural gas flows, had led to a spike in oil prices well above $100 a barrel. Crude prices dipped to about $95 after reports of a possible second round of talks on Tuesday. The US treasury department has said it does not plan to renew a temporary easing of sanctions on Iranian oil aimed at easing war-related supply shocks. The initial authorisation allowed for the delivery and sale of Iranian crude and other petroleum products loaded onto ships before 20 March. The step was part of a series of measures launched by the Trump administration to quell skyrocketing energy prices. Meanwhile, Israel and Lebanon have held unprecedented negotiations in Washington about the cross-border conflict, which erupted as a consequence of the US-Israeli attack on Iran. Hezbollah sided with Iran and launched rockets at Israel, which responded with intense bombardment of Beirut and other cities, and launched an invasion of southern Lebanon. In a statement after the two-hour session ended, the US state department praised the two sides for what it called “productive discussions on steps toward launching direct negotiations between Israel and Lebanon.” Hezbollah has said it will not abide by any agreements made by Israeli and Lebanese government negotiators in Washington. An Iranian official accused the US delegation of making maximalist demands at the Islamabad talks. “Iran did not surrender at the battlefield, neither will it surrender behind the table,” the official said. It is unclear where negotiations stood when the Islamabad meeting broke up over the other major proliferation concern: Iran’s stockpile of highly enriched uranium (HEU). It is close to weapons-grade purity and is believed to be buried in deep shafts under mountains in central Iran. At negotiations in Geneva before the war, Iran offered to dilute the HEU, which would extend the period it would take to produce a nuclear warhead, but the US has called for its complete removal. Pakistan’s prime minister, Shehbaz Sharif, is due to depart on Wednesday on a trip to Saudi Arabia, Turkey and Qatar to build support for the peace process, and to seek help with proposals to reopen the strait of Hormuz and discuss Iran’s demand for war reparations. Sharif’s regional tour might have to be cut short, however, if there is a quick return to the negotiating table. #pakustan#sharif#negotiations#trump#iran 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5626 · 15.04.2026 г., 13:59

Trump Has Taken a Tumble in Peace Talks With Iran. Will He Reset Them? 🔤🔤🔤🔤1️⃣ Trump has said that US-Iranian peace talks could resume in Islamabad over the next two days, and complimented the work of Pakistan’s army chief as mediator. The US president was speaking on Tuesday to a New York Post reporter who had gone to Islamabad for the first round of ceasefire talks over the weekend. After an interview discussing prospects for negotiations, the reporter said the president had called her back “with an update”. You should stay there, really, because something could be happening over the next two days, and we’re more inclined to go there,” Trump said. He added that Pakistan’s army chief, Field Marshal Asim Munir, was doing a “great job” in arranging the talks. “He’s fantastic, and therefore it’s more likely that we go back there,” Trump said. Munir is a powerful figure in Pakistan and has good relations with Trump, who has called him his “favourite field marshal”, and with Iran’s Revolutionary Guards. A Pakistani official said on Tuesday that he expected talks to restart soon, but it may take a day or two longer than Trump suggested. “The game is on,” the official said. Islamabad is racing to arrange a meeting date that provides enough time for negotiations before the two-week ceasefire ends on Wednesday 22 April. Trump’s comments followed a wave of speculation about a new round of negotiations, after 21 hours of talks on the weekend. Those ended Vance walking out on Sunday morning, claiming that Iran had failed to make an “affirmative commitment that they will not seek a nuclear weapon.” After the talks ended, Trump declared a US naval blockade on ships using Iranian ports in the Gulf in an effort to increase pressure on the country’s economy, and as a counter to Iran’s near-total closure of the strait of Hormuz to ships using other Gulf ports soon after the US-Israeli attack began on 28 February. US Central Command reported that over a 24-hour period “no ships made it past the US blockade and six merchant vessels complied with direction from US forces to turn around to re-enter an Iranian port on the Gulf of Oman.” #pakustan#sharif#negotiations#trump#iran 📱American Оbserver - Stay up to date on all important events 🇺🇸