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

Резултати

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

Пребарај: #leisure

当前筛选 #leisure清除筛选

uShaka Marine World is a popular theme park that opened in 2004 in Durban, KwaZulu-Natal. The park is divided into four main sections: • uShaka Sea World – one of the largest aquariums in the world, ranked fifth globally. • uShaka Wet 'n Wild – a water park with thrilling slides and pools. • uShaka Beach – a scenic beach area perfect for relaxation and water sports. • uShaka Village Walk – a lively shopping and dining area with various stores and restaurants. The aquarium, designed to resemble a shipwreck, is home to dolphins, sharks, seals, penguins, turtles, and many species of fish, some of which are endangered. Visitors can enjoy spectacular dolphin and seal shows, dive into the aquarium with sharks in a special cage, or snorkel among colorful tropical fish. For children up to 12 years old, uShaka Kids World offers a massive play area with exciting rides, water slides, a giant sandbox, and creative activity spaces. 🌐Official Website: ushakamarine.com 🎥Video from uShaka Marine World:Watch here. #tourism#leisure

Diving in South Africa offers unforgettable adventures for everyone! From exploring the magical kelp forests with playful seals in Cape Town to thrilling close encounters with sharks along KwaZulu-Natal’s subtropical South Coast, every dive is a new discovery. Don’t miss the once-in-a-lifetime experience of the Sardine Run in Sodwana Bay—a true spectacle of nature. Discover the breathtaking beauty of South Africa both below and above the water. 🎥 Watch the video: Dive into Adventure #tourism#leisure

Henry, the world's oldest known crocodile, resides at the Crocworld Conservation Centre in Scottburgh, KwaZulu-Natal, South Africa. Born on December 16, 1900, in Botswana, Henry once gained infamy for preying on local children before being captured in 1903. Now a beloved zoo attraction, Henry has fathered over 10,000 offspring with six mates. Weighing 700 kilos and measuring 16 feet [4.9 m] in length, Henry's long life and prolific breeding highlight the resilience of Nile crocodiles and the importance of conservation. Source: Times of India http://timesofindia.indiatimes.com/articleshow/113071729.cms?utm_source=contentofinterest&utm_medium=text&utm_campaign=cppst Video: https://t.me/NationGeographic/9647 #nature#leisure

🐒Добро пожаловать в «Манкилэнд» (Monkeyland) – рай для приматов в Южной Африке!🌿 Недалеко от Плеттенберг-Бей, в 500 км к востоку от Кейптауна, находится «Манкилэнд» – первый в мире заповедник, где приматы свободно разгуливают в естественной среде. Здесь обитают спасённые обезьяны со всего мира: капуцины, лемуры, гиббоны и многие другие. Интересный факт: В «Манкилэнде» находится 128-метровый подвесной мост – самый длинный в мире! Готовы к захватывающему приключению? 🎥Видео: #туризм#отдых ___________________ 🐒Explore Monkeyland: A Primate Paradise in South Africa! 🌿 Located near Plettenberg Bay, about 500 km east of Cape Town, Monkeyland is the world’s first free-roaming primate sanctuary. Home to rescued monkeys from around the globe, visitors can stroll through a lush forest and spot capuchins, lemurs, and gibbons swinging freely. Fun fact: Monkeyland has a 128-meter suspension bridge—the longest of its kind in the world! Ready for a wild adventure? 🎥Video #tourism#leisure

Вчера мы рассказывали вам о тематическом парке «Морской мир Ушака» (uShaka Marine World). Короткое видео было снято в парке представителем русскоязычной диаспоры ЮАР. 🎥Видео из «Морского мира Ушака». #туризм#отдых ___________________ Yesterday, we posted about the uShaka Marine World theme park. The short video was made in the park by a member of the Russian-speaking community in South Africa. 🎥Video from uShaka Marine World. #tourism#leisure

💎«Завтрак у Тиффани» Завтрак морских котиков в окрестностях Кейптауна. 🦭 #Природа#Туризм#Отдых ___________________ 💎 Breakfast at Tiffany’s Seals are having breakfast not far from Cape Town. 🦭 📹https://t.me/annauar/2469 #Nature#Tourism#Leisure

В часе езды на юг от Кейптауна, в уютном Саймонстауне, находится знаменитый пляж Болдерс (Boulders Beach), где обитает колония очаровательных пингвинов. Это одно из немногих мест в мире, где можно увидеть африканских пингвинов вблизи в их естественной среде. 📹Видео #природа#туризм#отдых ___________________ Just an hour’s drive south of Cape Town, in the charming town of Simon’s Town, lies the famous Boulders Beach, home to a colony of adorable penguins. It’s one of the few places in the world where you can see African penguins up close in their natural habitat. 📹Video #nature#tourism#leisure

☕️Heaven Coffee Shop at the Cape Town Methodist Church A small coffee shop inside a large historical church is a unique and atmospheric experience. You can freely stroll around the hall, play chess, enjoy great coffee with desserts, and take beautiful photos. 📸 🕊Tip: Take your time — the space invites relaxation and admiration of the architecture. 🔗https://t.me/capetown_in_russian/1232 #CapeTown#Coffee#Leisure#Tourism#HeavenCoffeeShop

🖼Boulders Beach — Penguins on the Beach! 🌊 The beautiful Boulders Beach is one of Cape Town’s most visited and the only place in the world where you can get this close to African penguins. 🐧 The Boulders Penguin Colony in Simons Town is home to a unique and endangered land-based colony of African Penguins — one of only a few in the world. This site has become a famous international tourist destination. The Boulders section of Table Mountain National Park consists of three pristine beaches, one penguin-viewing area, and three wooden boardwalks — built to let visitors admire these wonderful birds while keeping them safe. Thanks to the huge boulders that shelter the cove from currents, wind, and waves, it’s one of the best spots in Cape Town for both penguins and people. 🌴 🎥 Watch the video: https://www.youtube.com/watch?v=yDiVyXEbiNE #SouthAfrica#CapeTown#Tourism#Leisure#Nature#Travel#Penguins

В ЮАР существует необычная профессия — наблюдатели за акулами (shark spotters). Их задача — следить за океаном и предупреждать сёрферов и отдыхающих на пляже при появлении акул вблизи побережья. Как именно они выполняют свою работу? Узнайте из видео! _____________ In South Africa, there is a job called shark spotters. They are supposed to warn surfers and swimmers if a shark is spotted in the distance. How do they do it? Watch the video. Видео / Video: https://t.me/prixodite_lyudi_vAfriku_gulyat/2498. #отдых#пляжи#туризм #leisure#beaches#tourism

🇿🇦🏔 World’s Longest Zip Line — Just Outside Cape Town! In 2024, K3 South Africa Forest Adventures launched a 3.2 km zip line — the longest in the world. It’s located in Caledon, about an hour from Cape Town, with a 500-meter drop and speeds of up to 120 km/h! 💨 📹 Video: https://www.youtube.com/watch?v=Jutf87MXLsE #SouthAfrica#CapeTown#Tourism#Adventure#Leisure#Extreme#Travel

12
ПретходнаСтраница 1 од 2Следна