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

Резултати

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

Пребарај: #ramadanchallenge

当前筛选 #ramadanchallenge清除筛选
WESTER School

@wester_uz · Post #3561 · 11.03.2025 г., 00:00

#RamadanChallenge Lesson 2:🎬 📌Listening: Types of Listening Questions Part 1 and Part 2 👨‍🏫 Speaker: Mr. SaidIslom - Overall: 8.5 (Listening:9.0) 📆 Date: 11.03 ⏰ Time: 06:00 Venue: 📌@westerschool_IELTS

Doniyor Olimjonov English | IELTS

@doniyorieltss · Post #1227 · 24.03.2023 г., 11:15

Many governments think that economic progress is their most important goal. Some people, however, think that other types of progress are equally important for a country. Discuss both these views and give your own opinion. It goes without saying that for a nation to flourish its economy needs to be robust, which may lead many authorities to believe that developments in this field should be their sole priority. However, I believe that there are other, possibly more important, aspects to consider. The natural instinct, when a nation is on the brink of a development or recession, is to question its economic soundness. After all, it is wealth that decides a country's fate in most cases. Take the UAE, a previously desolate dessert that is currently home to hundreds of thousands of high-rise buildings. If it hadn't been for its rich natural resources, it wouldn't have gone from abject 'nothingness' to what is now known as the richest nation in the world. In addition to its affluency, this nation is also renowned for its rich culture, which could be explained by the fact that it is a mainstream tourist destination. People from all backgrounds flock to this place in search of a better life, making it all the more popular. Thus, it is safe to say that the economy should, in fact, get a lot of the attention. But it would be unfair if the economy alone received all the credit for a nationwide success. There are usually other rather obscure sectors that inevitably spotlight economic developments as being responsible for any type of improvement in a country. Without a healthy population, for example, it is almost impossible for a society to exist, let alone thrive. One such example is Africa where, despite its rich resources, sickness and poverty run rampant. The economy doesn't signify at this point, as all the existing resources are squandered on treating the ever-increasing diseases. Education plays another important role in this regard. Having quality or poor education can mark the difference between a bright and a grim future for young people that will one day contribute to the national workforce. In other words, it is schools where any type of development begins. Economic strides are certainly essential — it is thanks to them that a country can compete with its counterparts in wealth and power. However, there won't be an economy to boost unless other types of progress, such as the medical and educational ones, receive the same level of attention, if not more. After all, these are the stepping stones to improved economy, which is the path to a better future. #MyWriting#RamadanChallenge @ieltsulugbeks

Doniyor Olimjonov English | IELTS

@doniyorieltss · Post #1220 · 23.03.2023 г., 02:44

#WritingTask2#Economy#RamadanChallenge Many governments think that economic progress is their most important goal. Some people, however, think that other types of progress are equally important for a country. Discuss both these views and give your own opinion. I will soon send my plan and sample answers for this task. @ieltsulugbeks