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

Пребарај: #frustrated

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

@american_observer · Post #5468 · 25.03.2026 г., 18:01

🔠🅰️🔠🔠2️⃣ Some cynics also note that the president’s pause will last throughout the trading week on global markets. With stock futures tumbling and oil prices soaring coming out of the weekend, was he simply seeking to stitch a cushion of market stability? It wouldn’t be the first time that official statements seemed aimed at taming volatility. And it worked again: The Dow, the S&P 500 and the Nasdaq all rose over 1% Monday, while Brent crude, the global oil benchmark, fell 11%. US drivers will hope for a break at the gasoline pumps. Trump may want to buy time for another reason: The US forces that might give him the option to invade Kharg Island — the epicenter of Iran’s oil industry and a vital economic hub — or to occupy islands and coastal regions in the Strait are not yet fully assembled. One US Marine Expeditionary Unit that deployed from Japan may reach the region soon. But a second only set off from the West Coast last week. It’s also worth remembering that Trump loves hyperbole. Experience suggests that his hyping of diplomatic progress and claims Iran “badly” wants a deal may be overstatements — even if deliberate deception is sometimes a tool statesmen use to create space for breakthroughs. The president’s wild gyrations that had him talking about “winding down” the war one day and escalating it the next were incompatible with the traditions of stable war leadership. But they were quintessential Trump. By Monday, it all looked like a ruse to allow him to argue his hard-man tactics had forged diplomatic progress. This unpredictability and tendency to try to mitigate his self-created crises is familiar from Trump’s personal life and his business and political career, as well as his multiple scrapes with the justice system. Each day often unfolds as a quest to remain standing by nightfall. With this technique, Trump delays reckonings and defers the worst consequences of his actions in an endless improvisational dance. Yet there’s a sobering possibility that Trump’s erratic method may be tested beyond its limits in the Persian Gulf. Iran might be outgunned by the US and Israeli assault and suffering extremely heavy losses to its naval, air and land-based assets during a war that has wiped out senior members of the Islamic clerical regime. But as the conflict enters a fourth week, it’s also demonstrated its own leverage after effectively closing the Strait of Hormuz and holding the global economy — and Republican political hopes in November — hostage. Logic suggests a regime that was already ultra-radical before the war is unlikely to be more open to Trump’s demands after the killing of its supreme leader and enduring an onslaught from US and Israeli missiles and jets. Trump’s terms for ending the war — likely to include Iran renouncing its nuclear program and long-range ballistic missiles — may be deal-breakers. That’s because the last three weeks show exactly why a rogue regime might decide to pursue such insurance policies against future attacks by foreign powers. Even if talks do open — and Pakistan has offered to hold them — it’s not clear who would be negotiating for Iran. A regime that has decentralized authority and lost key figures may struggle to make collective decisions. And if, as some experts believe, the Islamic Revolutionary Guard Corps are now in full control, it might be even more hardline than before. Moreover, in the past Washington has spoken to relatively moderate Iranian officials, only to find more radical figures set against compromise. It also would not be surprising if Iran’s leaders interpret the president’s reversals, contradictions and emotional social media posts as signs that their strategy of imposing economic consequences on Trump is working. #trump#frustrated#tehran#guard#corps#israel 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5467 · 25.03.2026 г., 16:03

Trump Had Grown Frustrated With Tehran: the War Is Not Over 🔠🅰️🔠🔠1️⃣ Wars, unlike illegal tariffs, cannot be switched on and off to meet a president’s whims or to permanently shore up free-falling markets. So the key question following President Donald Trump’s suspension of threatened strikes against Iran’s power plants is not whether he’s had another TACO (“Trump always chickens out”) moment. It’s whether Trump can get out of his war on Iran, even if he wants to. After days of oscillating rhetoric, Trump signaled a first potential de-escalation in the conflict Monday, when he cited 15 points of agreement in what he said were productive talks with Iran. Tehran said there’d been no dialogue. The most hopeful spin on the latest developments is that US and Iran have both reached a point where the cost of climbing the escalation ladder would be so horrific that both need a way out. Such epiphanies can begin to end wars. An oil tanker sits anchored as the traffic is down in the Strait of Hormuz in Muscat, Oman, on March 10. Trump had dragged the enemies to the brink by threatening to bomb Iran’s power plants if it didn’t open the Strait of Hormuz, a chokepoint for oil exports. Tehran had promised to retaliate by torching vital infrastructure in US-allied Gulf states. The conflagration could have set off a global recession and worsened dire humanitarian conditions for the very Iranian civilians Trump pledged to help. But there are many reasons for skepticism that a breakthrough is imminent. Days of erratic, contradictory rhetoric from Trump and the administration’s inability to cite a consistent rationale for the war or to plot an exit strategy mean that any single US statement lacks credibility. The president’s habit of bombing during his own deadlines in Iran mean no one would be surprised if he broke his own five-day moratorium on striking the country’s power plants. #trump#frustrated#tehran#guard#corps#israel 📱American Оbserver - Stay up to date on all important events 🇺🇸