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

Резултати

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

Пребарај: #trending

当前筛选 #trending清除筛选
TODAY

@todayonlinesg · Post #19412 · 30.09.2024 г., 11:23

#trending: Teenager who has autism waits an hour at Jurong East MRT Station with no train service, mum goes to his aid "The problem was that he didn’t know what his next step should be. At the same time, he may have been hoping that the train would arrive later." Ms Lydiawati Ismail said of her son who has autism. 🚇https://tdy.sg/3NajJLe @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19346 · 16.09.2024 г., 13:57

#trending: Father-daughter dance at competition goes viral, viewers say it made them cry or think of their own dads They won a “special mention” medal and they were also the oldest and youngest participants in the open category, Mr Jay Sng said. 🤸‍♂️🧑‍🧒https://tdy.sg/3XkEgla @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19315 · 12.09.2024 г., 09:30

#trending: S'pore woman's biggest culture shock living in Sweden? Many couples skip marriage even after kids Ms Wynnette Yip said that she has been in a relationship with her Swedish partner for eight years and often faces questions from friends and family in Singapore on whether her other half was ever going to propose to her or was simply "wasting (her) time". 🇸🇪https://tdy.sg/3ZpFcHx @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19299 · 10.09.2024 г., 09:04

#trending: 'Full-on racial harmony' — video of Chinese S'porean youths loving Tamil movie goes viral Many netizens found it refreshing and heartwarming to see Chinese youths so thoroughly enjoying a film of a different language and culture, with users calling their reactions "cute" and "awesome". 🎬https://tdy.sg/3AQNKwP @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19292 · 09.09.2024 г., 10:54

#trending: 'Completely drained' — British expat's tale of long hours in China's tech sector goes viral Many social media users in China were amused to see a foreigner grappling with the demanding work culture in their country. 🇨🇳https://tdy.sg/4egs2Ry @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19272 · 06.09.2024 г., 12:24

#trending: S'pore non-profit that staged TikTok video of man harassing woman sparks debate on when to step in to help others TikTok users have lauded real-life passers-by who chose to intervene and help the woman, not realising that it was a staged incident. They said that it is important to look out for each other. ➡️https://tdy.sg/3Xcbx1X @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19147 · 20.08.2024 г., 10:37

#trending: SIA flight attendant praised as 'angel' for helping passenger clean jeans using own stain remover pen In a "friendly chat" with a cabin crew member she referred to as Aiden, Ms Paige Parker asked him "almost jokingly" if SIA had any stain removers, expecting the answer would be no. ✈️https://tdy.sg/3AxJC4T @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19134 · 19.08.2024 г., 09:31

#trending: Is Amsterdam safer? S'porean woman's reasons for moving to the Netherlands spark debate online Aside from her safety concerns, the weather was a major factor, as she found Singapore too hot and humid. "I can't be sweating perpetually," she wrote. ➡️https://tdy.sg/3Ti9EQf @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19101 · 15.08.2024 г., 11:27

#trending: Japanese ramen shop ranks Singaporeans’ spice tolerance as ‘mid’; netizens agree Out of 10 levels, Singapore and Malaysia are ranked in the middle while Indonesia is at the top with the highest spice tolerance. ➡️https://tdy.sg/4fNFrBQ

Hashtags

TODAY

@todayonlinesg · Post #19067 · 13.08.2024 г., 11:03

#trending: Influencer's praise of NDP crowd control leaves S'poreans grateful for reminder 'we are so blessed' Ms Francesca Tanmizi, an Indonesian who lives in Singapore, told her 316,000 TikTok followers she was wowed by the efficiency of NDP crowd control, the speedy cleanup of rainwater and the friendliness of the personnel involved. 🇸🇬https://tdy.sg/3WByhIk @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #19057 · 12.08.2024 г., 11:40

#trending: New S'pore teen character in Marvel comic book sounds like burnt-out student, say netizens A Redditor teased that the character's powers could be “the result of years of training by her kiasu Tiger mum under the Singapore academic system” rather than an actual superpower. 👩‍🎓https://tdy.sg/4dFadep @todayonlinesg

Hashtags

TODAY

@todayonlinesg · Post #18965 · 01.08.2024 г., 11:40

#trending: Netizens praise Jetstar Asia's 20th anniversary song for celebrating uniquely Singaporean traits One viewer wrote: "Please consider (Mr Van Der Ven) for NDP theme song. He writes his own music and can supply 20 different types of aunties." ➡️https://tdy.sg/3WqSn85

Hashtags

123•••10•••20•••303132
ПретходнаСтраница 1 од 32Следна