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

Пребарај: #nationalday

当前筛选 #nationalday清除筛选
Embassy of Russia in Singapore

@rusembsg · Post #3154 · 12.06.2024 г., 02:08

On June 11, 2024, Russian Embassy in Singapore hosted a state reception dedicated to the #NationalDay of the Russian Federation – Russia’s Day. Minister of State for Culture, Community and Youth, Minister of State for Trade and Industry, H.E. Mr. Alvin Tan attended the function as the Chief Guest. Among the guests were Members of the Parliament of Singapore, eminent representatives of business and social, scientific and cultural community, mass media along with Ambassadors and Military Attaches of foreign states and Russian compatriots. In his welcoming speech, Ambassador stressed that Russia remembers and appreciates that Singapore and other ASEAN countries were among the first to recognize the new Russia. He stated that thanks to this step, we have the opportunity today to look together into the face of the emerging new, fair, multipolar world. Ambassador continues mentioning that “even though large distances separate us, even though the natural and geographical conditions in which we have to live vary, even though we have different views with Singapore on the parameters of regional architecture and the genesis of the events in Ukraine, there is something very significant that connects us and is the subject of our common daily concerns”. “This connecting link is the mutual concern about the threats created by the arms race and the prospect of its spreading into outer space! This connecting link remains the common resistance to the dangers created by terrorism, transnational crime and the money laundering schemes that feed them! We rightfully consider our devotion to the ideals of building a drug-free world to be this connecting link! We consider our common efforts to guarantee international information security to be this connecting link, which would securely block the destructive use of the information environment! And finally, closer to the venue of our meeting today, we see such a link in cooperation for building an open and inclusive, free, predictable region based on the inviolable principles of ASEAN centrality”, he noted. “We invite you to take a closer look at the concept of the Greater Eurasian Partnership that we are promoting and to join the triptowards a new, common and indivisible formula for security in Asia and the Pacific as an alternative to conflicting Indo-Pacific concepts of the collective West. I am convinced that our cooperation has a bright future. It should contribute to the creation of a new world community free from the remnants of colonialism”, concluded the Ambassador.

Hashtags

聖小熊的秘密基地 🇹🇼

@holybeartw · Post #1213 · 10.10.2025 г., 10:18

🇹🇼 祝大家國慶連假快樂!🇹🇼 中華民國屹立於台灣之島,雖身處天災頻發與地緣緊張的前線,一路以來戰戰兢兢、克服一切困難。 我們或許時有歧見與爭論,然而「團結」始終是這片土地上最堅韌而無畏的力量。願我們在相互理解與信任之中,持續邁向更具包容與希望的社會。 中華民國台灣萬歲! #NationalDay#ROC#Taiwan