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

Резултати

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

Пребарај: #kenyan

当前筛选 #kenyan清除筛选
Addis Standard

@addisstandardeng · Post #21462 · 20.02.2026 г., 08:42

#Russia denies of recruiting #Kenyan citizens for war in #Ukraine The Embassy of the Russian Federation in Kenya has rejected allegations that it was involved in recruiting Kenyan citizens to fight in the conflict in Ukraine, describing the claims as part of a “dangerous and misleading propaganda campaign.” In a press release issued on February 19, the embassy said it had observed with “great concern” reports circulating in Kenyan media and public discourse regarding Kenyan nationals who allegedly traveled to Russia, joined the Armed Forces of the Russian Federation, and participated in combat operations in Ukraine. The statement comes after an intelligence official briefing presented to Kenya’s Parliament reported that 89 Kenyans were confirmed on the front line, 39 were hospitalized, and 28 were missing in action. https://addisstandard.com/?p=55260

Addis Standard

@addisstandardeng · Post #21908 · 01.04.2026 г., 16:28

Shipping disruptions strand 8 million kg of #Kenyan tea in #Mombasa as #US-#Israel war with #Iran hits exports Disruptions to global shipping routes linked to the ongoing war between the United States, Israel, and Iran have left nearly eight million kilograms of tea stranded in warehouses in Mombasa, threatening export earnings and farmer incomes, according to the East Africa Tea Traders Association. George Omuga, managing director of the association that runs the Mombasa tea auction, told Reuters that losses have been accumulating at roughly $8 million per week since 01 March. “The current conflict in the Middle East has had a direct impact, a negative impact on this auction,” Omuga said, noting that no tea shipments were currently leaving for Middle Eastern markets, which account for 20–25% of Kenya’s tea exports. https://x.com/addisstandard/status/2039378986518626404?s=20

Addis Standard

@addisstandardeng · Post #21163 · 23.01.2026 г., 09:22

News: #IMF-backed forex reforms cost #Ethiopia $2.6 billion in central bank losses Ethiopia’s central bank, the National Bank of Ethiopia (#NBE), has recorded losses equivalent to $2.6 billion following the country’s shift from a fixed to a market-based foreign exchange regime in July 2024, according to audited financial statements cited by the #Kenyan outlet The EastAfrican. NBE said it incurred 407.1 billion birr in foreign exchange losses during the financial year ending June 30, 2025, largely due to the revaluation of its foreign currency assets and liabilities after the exchange rate realignment. Foreign exchange losses rose sharply to 445.23 billion birr, from 38.13 billion birr the previous year. The surge pushed the National Bank of Ethiopia’s overall operating loss to 428.56 billion birr, up from 10.51 billion birr a year earlier, and drove the Bank into a negative equity position of 380 billion birr, raising concerns over its ability to continue... Read more: https://addisstandard.com/?p=54706

Addis Standard

@addisstandardeng · Post #21956 · 07.04.2026 г., 05:28

#UN envoy meets RSF leader in #Nairobi to discuss de-escalation in #Sudan The United Nations Personal Envoy for Sudan, Pekka Haavisto, met with Rapid Support Forces (#RSF) commander Mohamed Hamdan “Hemetti” Dagalo in Nairobi on Monday to discuss practical avenues for de-escalation. The meeting in the #Kenyan capital is part of Haavisto’s inaugural regional tour. It follows recent discussions in Khartoum with the President of the Transitional Sovereign Council, General Abdel Fattah al-Burhan, as the UN seeks to mediate an end to the nearly three-year-old conflict. UN spokesperson Stéphane Dujarric described the talks as a “constructive opportunity” to exchange views on protecting civilians. He noted that all stakeholders engaged by Haavisto have expressed readiness to cooperate with the world body. “This is encouraging and must swiftly translate into concrete progress towards ending..... https://www.facebook.com/AddisstandardEng/posts/pfbid0KVXwXxdPxbctPJpW5qK7Kwkw63bPeXrmU7q7Bjab37CvbqfZT7SuvSHFZqa4GrN2l