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

Пребарај: #squadgames

当前筛选 #squadgames清除筛选

🤝$300 Spread the Word Contest — Create Content & Get Rewarded! In anticipation of the start of Squad Games Season 2, the #Electra team is launching a creative competition for the community with a prize pool of $300 USDT! You create content and get a chance to win a prize! 💸 ✔️How to participate? 🟢 Make a post/video/image about Squad Games Season 2 🟢 Post it on one of the platforms with the hashtag #electra: 🌐Twitter (X) 🌐TikTok 🌎Instagram Reels 📺YouTube Shorts 🟢 Leave a link to your content in the comments below ➡️the original post by Electra 💵Awards: 300 USDT will be distributed among 5 authors of the most viral and creative works. Each winner will receive 60 USDT. 🗓Deadlines: up to and including May 26, hurry up! 🤑Electra is once again encouraging creativity and community — if you've been wanting to prove yourself, this is the perfect chance. #Electra#SquadGames#Contest

🤝Squad Games Season 2 by Electra – MORE REWARDS, MORE ACTION! After a successful first season, #Electra launches Squad Games Season 2 — this time with even higher stakes: more prizes, more bonuses, more winners, and more opportunities for active traders! 📅 Tournament Start: May 26 🕓 Duration: 2 weeks 💵Squad Rewards: 💲 Up to $100,000 USDT 🎁 Up to $100,000 in bonus vouchers ⚡️5,000,000 airdrop points *Rewards will be distributed among the top 20 traders by volume in each of the top-6 squads. 💵Individual Rewards: 💲 $5,000 USDT will be shared among the top-20 traders with the highest PnL (in USDT) throughout the tournament. 💵 Daily Bonuses — $50 each*: ✅Best PnL of the day ✅Worst PnL of the day ✅Highest daily trading volume *Rewards are issued as Electra bonus vouchers and will be distributed after the tournament ends. 🤑Just like in Season 1, all trading activity counts toward farming points for the upcoming $ELT airdrop! So by participating in the tournament, you’re not only competing for real rewards, but also boosting your future $ELT airdrop share. ⚡️ Electra also teased $ELT tokenomics: • TGE supply — 100,000,000 $ELT • Up to 10% allocated to the community airdrop • 5,000,000 $ELT were already distributed in Season 1 • Season 2 has a significantly larger allocation focused on active traders and volume! 📈Took part in the Storm Trade contest and liked the vibe? Then Squad Games by Electra is your next-level challenge: ✅ Bigger rewards ✅ $ELT farming ✅ Real incentives for your trading activity 🤑 The tournament is live!Join our squad, farm points and claim your share of rewards! ❤️TON Events Squad🧪 #Electra#SquadGames#Season2#Airdrop

🤝Squad Games Season 2 by Electra – MORE REWARDS, MORE ACTION! After a successful first season, #Electra launches Squad Games Season 2 — this time with even higher stakes: more prizes, more bonuses, more winners, and more opportunities for active traders! 📅 Tournament Start: May 26 🕓 Duration: 2 weeks 💵Squad Rewards: 💲 Up to $100,000 USDT 🎁 Up to $100,000 in bonus vouchers ⚡️5,000,000 airdrop points *Rewards will be distributed among the top 20 traders by volume in each of the top-6 squads. 💵Individual Rewards: 💲 $5,000 USDT will be shared among the top-20 traders with the highest PnL (in USDT) throughout the tournament. 💵 Daily Bonuses — $50 each*: ✅Best PnL of the day ✅Worst PnL of the day ✅Highest daily trading volume *Rewards are issued as Electra bonus vouchers and will be distributed after the tournament ends. 🤑Just like in Season 1, all trading activity counts toward farming points for the upcoming $ELT airdrop! So by participating in the tournament, you’re not only competing for real rewards, but also boosting your future $ELT airdrop share. ⚡️ Electra also teased $ELT tokenomics: • TGE supply — 100,000,000 $ELT • Up to 10% allocated to the community airdrop • 5,000,000 $ELT were already distributed in Season 1 • Season 2 has a significantly larger allocation focused on active traders and volume! 📈Took part in the Storm Trade contest and liked the vibe? Then Squad Games by Electra is your next-level challenge: ✅ Bigger rewards ✅ $ELT farming ✅ Real incentives for your trading activity 🤑 The tournament is live!Join our squad, farm points and claim your share of rewards! ❤️TON Events Squad🧪 #Electra#SquadGames#Season2#Airdrop