Что делать если нужно поставить какую-то 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
🤝 Partnership: DejenDog X Pirate Frenzy
We’re super thrilled to announce our collaboration with DejenDog, a #Tap2Earn game based on Telegram and incubated by HashKeyWeb3. Hit to earn $HIT and get a chance to win additional $HSK.
They’re launching a 10 Million $HSK Airdrop campaign on DejenDog 🪂
️🎉 As the Official Airdrop channel for the $HSK program, DejenDog will offer our community an extra 300,000 $HIT per player.
👉 Head over to the DejenDog Mini App to claim yer eligible $HSK tokens:https://t.me/DejenDogBot?start=d02e7d44
👉 DejenDog Channel: https://t.me/DejenNews
- - -
Website | Twitter | TG Channel | TG Community | Discord
• Pirate Frenzy (Play-To-Airdrop Mini App on Telegram)
• Pirate Clash (Extension directly playable on Twitter)
🤝 Partnership: Mappasaurus X Pirate Frenzy
We are pleased to announce our collaboration with Mappasaurus, leveraging advanced AI and decentralized tech to develop a dynamic, constantly evolving global map.
🦖 Crackasaurus is their TON-based #Tap2Earn game where tapping earns you $CRACKA, the in-game currency. Climb the leagues to unlock unique NFTs with special benefits in the Mappasaurus ecosystem.
🤑Tap to Earn with Crackasaurus now: https://t.me/MappasaurusAppBot/Crackasaurus?startapp=piratefrenzybot
Check out for more details: https://x.com/PirateClash_HQ/status/1810730983471350090
- - -
Website | Twitter | TG Channel | TG Community | Discord
• Pirate Frenzy (Play-To-Airdrop Mini App on Telegram)
• Pirate Clash (Extension directly playable on Twitter)
New Listing OFFICIAL - $AVACN@avagoldcoin
🔹 Pair: AVACN/USDT
🔹 Deposit: Open NOW
🔹 Trading starts: July 30, 10:00 AM (UTC)
Join Bitgets #Tap2Earn $AVACN campaign to celebrate the listing!
Get a 5% daily boost on your deposit to #Bitget and earn $20 AVACN with a simple daily tap. 🚀
How to join?
☑️ Use the AVACOIN bot and complete #Bitget tasks: t.me/avagoldcoin_bot
👉 First sign up here: https://bonus.bitget.com/ALAA4W
👉 Then learn more here: https://www.bitget.com/events/tap-to-earn-more
🚀 Exciting Partnership Announcement!
We're thrilled to join forces with GPTWars, the first AAA game on ton blockchain!
Get ready to infiltrate, survive, and restore balance together. This marks a new era in gaming innovation and community engagement.
Stay tuned for more updates and epic adventures!
📲Join our awesome crew on Discord and stay updated on news: https://discord.gg/metafighter
Tweet 🔗:https://x.com/gametyio/status/1817096006208471440
Like, RT and comment the post to make some noise
📎Important Links:
Website | X | Chat | Discord | Announcement | Youtube
#tap2earn#play2earn
📢 Exciting Partnership Announcement!
We’re thrilled to announce that Gamety is now partnered with ElfinGames, the 1st GameFi Omni Layer focused on eSports! 👾
✨ Elfin Metaverse, backed by @BinanceLabs, is an all-in-one eSports gaming platform and open-world metaverse built on Elfin Lands, a virtual realm that offers a unique gaming experience and a thriving community!
🤝 Elfin Metaverse is joining the Gamety Fam with co-campaigns, AMAs and other fun community events.
📢 Stay tuned for any future updates on Gamety and the Elfin Lands.
Use Gamety unique invitation code: https://elfinmetaverse.com/?inviteCode=9XYZUC20 to earn more in Elfin Metaverse!
📲Join our awesome crew on Discord and stay updated on news: https://discord.gg/metafighter
Tweet 🔗:https://x.com/gametyio/status/1816761387005116529
Like, RT and comment the post to make some noise
📎Important Links:
Website | X | Chat | Discord | Announcement | Youtube
#tap2earn#play2earn
🔥 We've reached an incredible milestone of 100,000 Gamers in our#Tap2Earngame and the Fun's just starting 🚀
The best#Rewardsand#Opportunitiesare yet to come. Don’t miss out on this adventure.
🕹️Play#Crackasauruson @Telegram, invite your friends and earn$CRACKA, while shaping the future of mapping.
🦖 Dinos, Should we celebrate this with a#MEMEcontest where the funniest one wins?
🤑Join the Game here: @MappasaurusAppBot
𝕏 Click to share it with your friend
👀Follow us on:
Twitter | Instagram | Medium | Youtube | Linkedin | Earn
🪙1 DAY to $TOMA
The team announced decision to allocate 80% of entire $TOMA supply to community members😄😄😄
The team believes that the users should receive the majority share. After all, without users, there is no project — your support is what made #Tomarket possible.
A few key details to keep in mind over the next couple of days. Read them carefully:
✔️ The countdown ends October 31st at 23:59 HRS. Be sure you’re ready because this is when we’ll lock in your $TOMA allocation. Reach the highest level you can — every bit counts.
✔️ For accurate $TOMA allocations, the game will undergo a 24-hour maintenance period after the snapshot. Most features will go offline, giving us the time we need to finalize each allocation and remove any unwanted bots or bad actors.
✔️ Note that at this point, level upgrades, payment functions (TON stars, payments with #TON), and activity for $TOMATO or referral counts will be stopped.
✔️ You’ll be able to view your $TOMA balance after November 2nd 00:00 HRS (GMT+8).
$TOMA is seriously coming. And this is just the beginning.
See you in about 28 hours.
Tomarket Team
Those who have achieved at least🏅Gold + Medal Owner🎖 might find there's a little extra waiting for them...
The last call guys, LFG!!😄
#Airdrop#TGE#listing#BitgetWallet#Web3#TON#Tap2Earn
There's a lot to be made by tapping and claiming coins from the Go! Ton App!
Get started Here: https://t.me/thegoprojectBot
This bot is your free pass to Sweet rewards, get started Now.
Once you get started, you've got to maintain your spot as a weekly and monthly active user. Here's why:
🔹 There are more rewards as you get more active
🔹 You get features nobody else gets
🔹 You get into higher ranks which means exclusive airdrops will be sent to you.
🔹 You get access to collectibles reserved just for you
🔹 You get to Contribute more to the community, and influence the direction of the project
Ready to start Tapping?
Let's Go: https://t.me/thegoprojectBot
#gotonapp#tap2earn#bot#rewards#boost#wealth
Join: 🐣X✉️Chat✉️News🤖Discord
Play: 🕹️TON App💻Web App
Info: 🖥Newsletter🌐Website🌐Blog