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

Пребарај: #jointprojects

当前筛选 #jointprojects清除筛选

✨️Ambassador Albert P. Khorev's Interview with “Mehran TV” Full interview available in Urdu Key points: #BilateralTrade 🔸️Over the past two years, the annual trade turnover between #Russia and #Pakistan has amounted to approximately $1 billion USD. Our governments understand that this figure does not reflect our countries' existing potential, and they are making efforts to deepen bilateral cooperation. One effective mechanism in this regard is the Intergovernmental Commission on Trade, Economic, Scientific, and Technical Cooperation, which will hold its 10th milestone meeting in November 2025 in Islamabad; 🔸️There is potential for increased fuel, petroleum products, and grain supplies from Russia to Pakistan, as well as for increased imports of Pakistani textiles, leather, and agricultural products to Russia; #JointProjects 🔸️We are considering a number of infrastructure projects, including the modernization or construction of a new Karachi Steel Mill and railway tracks, as well as the supply of Russian pharmaceutical products, with the option of joint production; 🔸️We look forward to implementing new projects in the energy and transportation sectors. Given the recent establishment of diplomatic relations between Pakistan and Armenia, we believe that a free trade agreement between Pakistan and the #EAEU is possible in the future; 🔸️The successful modernization of the Karachi Steel Mill will pave the way for more productive cooperation; #TradeInNationalCurrencies 🔸️Most of Russia's export operations with friendly countries, including #SCO member states, are conducted in national currencies. The US dollar is slowly but surely losing ground. The process of diversifying payment instruments is succeeding; #SituationInTheRegion 🔸️Russia respects the right of regional countries, including Pakistan, to choose their own foreign policy partners independently. South Asian countries' engagement with the West is an internal matter. However, we consider it inappropriate if such engagement is directed against any state or group of states; 🔸️We have noted the Americans' and their NATO allies' active efforts to return to #Afghanistan after their infamous retreat in 2021. Donald Trump's statements about the U.S.'s desire to retake control of the #Bagram Air Base and his demands that India stop purchasing Russian oil are unacceptable. They represent yet another manifestation of Western neocolonialism; 🔸️The recent SCO summit in China demonstrated the declining influence of extra-regional forces. There is a growing demand for Russian President Vladimir Putin's initiative to establish a Eurasian security system based on the principle of "regional solutions to regional problems;" #MoscowFormat 🔸️The Moscow Format Consultations bring together all of Afghanistan's neighboring countries, including Russia and Pakistan. This regional mechanism has proven its effectiveness. All its members agree that the return of U.S. and NATO military infrastructure to Afghanistan is unacceptable; #Kashmir 🔸️Pakistan and India inherited the Kashmir issue from their British colonial past. We believe that Islamabad and New Delhi should resolve their differences through political and diplomatic means. At the same time, if it receives appropriate signals from both sides, Russia is ready to contribute to improving relations between the two countries and make the necessary efforts in international forums, including the #UN. #RussiaPakistan