Что делать если нужно поставить какую-то 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
#Catizen announced that tonight at 00:00 UTC, they will take a snapshot 📸, and tomorrow at 10:00 AM UTC you can check how much airdrop ✈️ each user will receive.
💰 Each account can stake 1,000 CATI.
🎁 About $1 million in rewards have been allocated for staking.
🗓 The staking period is from September 14 to 24.
🚀 Starting Sunday, September 15, at 9:00 AM UTC, you can withdraw your airdrop to CEXs (centralized exchanges).
📈 Trading will also start on September 20.
🔮 They also mentioned that token holders will receive rewards in the future.
join Now:
https://t.me/catizenbot/gameapp?startapp=rp_9810907
@airdropgoldchannel
Share It!
🔍#Catizen Data Tracking
Catizen's built-in real-time data analysis with multidimensional data mining and machine learning optimizes game content, boosts user retention, and increases payment conversion. It supports custom reports and real-time monitoring for data-driven decisions. 📊✨
Catizen's vibe: Play for the airdrop🪂, Heal the world! 🌍
https,://t.me/catizenbot/👈
°°°
#Catizen values its users as the best investors. Airdrop increased from 35% to 42%! More kitty love, more rewards, more healing! 🌟🐱💎
Catizen's life: Play for airdrop🪂, Heal the world! 🌍
https://t.me/catizenbot/👈
°°°°°°°°
#Catizen cherishes its users and community as our greatest supporters. 🐱 Why? Because your love for cats deserves recognition.
That's why we've raised the airdrop from 35% to 42%, adding a total of 7%—all because of your incredible love and dedication.🎉
To celebrate reaching 20 million users, we're taking an extra 1% from investors, making the airdrop 42%! 🪙 Your unwavering support moves us forward!
🌟🐱💖
Catizen's vibe: Play for the airdrop🪂, Heal the world! 🌍
https'://t.me/catizenbot/👈
°°°°°°°
🌍🐾 Since the launch of Catizen's Spin, global players have collectively received a heartwarming 7 millionassists. 🤝🐱#Catizen not only heals the world through the power of cats, but also fosters mutual healing among players. 😻
Catizen's life: Play for airdrop🪂, Heal the world! 🌍
Catizen: 1 Million On-Chain Users, Paws-itively Healing the World!
🌍🐾#Catizen has hit a milestone with 1 million on-chain users, unleashing a tidal wave of feline healing across the globe! 🎉✨
Join the purr-fect revolution where virtual cats mend hearts, and a million paws unite for a happier world. 😺💖
Catizen's life: Play for airdrop🪂, Heal the world! 🌍
🏆Top 23 projects where you can earn $.
°°°
Bitget pre-market trading: 😸 Catizen ($CATI) is launched🔥
Bitget announced #Catizen token $CATI launch in pre-market trading. Users can trade CATI in advance, before it becomes available for spot trading.
Details are as follows:
Start time: 24 July, 2024, 10:00 (UTC)
Pre-market trading link: CATI/USDT
24h total (USDT): 143.88K
Last price (USDT): 0.99 (+98%) 🚀
Register now and trade your CATI!😼
💰#Catizen will list on #Binance
Users will be able to lock their BNB and FDUSD to receive CATI Airdrops over four days, with farming starting from 2024-09-16 00:00 UTC.
Binance will then list CATI at 2024-09-20 10:00 UTC and open trading with CATI/USDT, CATI/BNB, CATI/FDUSD, and CATI/TRY trading pairs.
join Now:
https://t.me/catizenbot/gameapp?startapp=rp_9810907
@airdropgoldchannel
Share It!
😸Catizen is distributing $CATI!
💭September 14, 00:00 UTC - Snapshot and maintenance.
🚀September 14, 10:00 UTC - Check your $CATI and start staking.
🪙September 15, 10:00 UTC - Claim to CEXs function will be available.
🏆Prize Pool: $1 million in tokens ($BGB, $GT, $KCS, $HSK, $MX).
📣Staking Period: September 14 - 24.
👉Stake $CATI and start earning!
🔕Subscribe👉Catizen
➖➖➖➖➖➖➖➖➖➖➖
#cryptogame#catizen#crypto
💰There's still time to catch the Catizen airdrop!
We remind you that within our channel there is a competition for the best miners, which makes it possible to receive additional profit for mining in our club. Since #airdrop has not yet been announced, there is still time to participate!
Prizes for leaders🎉TON Events:
🏆$150 to each player in the top 3
🏆$50 to each player in the top 4-10
🏆$20 per player 11-30
🏆$5 per player 31-100
A snapshot will be taken based on the weekly leaderboard at the time of the announcement of the airdrop from #Catizen. Prizes will only be paid if our club reached top 10 clubs of the Royal League. Hurry up to visit our club before the airdrop to get your prize!
Give me meow😼
Catizen Announcement: Welcome to Divine Area in Catizen Game Center
#Catizen#game
Catizen Announcement introduces Divine Area as the latest addition to Catizen Game Center. This magical realm offers a unique talent system and limitless lineup possibilities, encouraging fair competition. Use CATI for a 30% discount in the game.
Source: link
@tonlines