Что делать если нужно поставить какую-то 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
🌐The Internet's History
The #Internet's history goes back some decades by now – #Email has been around since the 1960s, file sharing since at least the 1970s, and TCP/IP was standardized in 1982. But it was the creation of the world wide web (www) in 1989 that revolutionised our history of communication. The inventor of the world wide web was the English scientist Tim Berners-Lee who created a system to share information through a network of computers. At the time he was working for the European physics laboratory CERN in the Swiss Alps.
The chart below shows the share and number of people that are using the Internet, which in these statistics refers to all those who have used the Internet in the last 3 months.
Read more on OurWorldInData and see the full-size chart here.
🚀@PerspectiveIX
Eppie — open protocol encrypted p2p email
=> https://eppie.io
=> https://github.com/Eppie-io
Eppie is a next-gen providerless email that allows its users to own their accounts, addresses and data. In addition to its own p2p network Eppie can communicate with other popular decentralized networks, like Ethereum, and is capable of interacting with conventional IMAP/SMTP email. It is beautiful and easy to use, just like a normal email client.
Features:
🌎 Works on all platforms: Windows, MacOS, Linux, iOS, Android
🕶 Privacy-first: there's no such thing as optional encryption
🚀 P2P messaging: without servers nobody's holding your hand anymore
🔑 Identity manager: key management is a breeze
💾 Decentralized backup: your data is safe and only yours
🤙 Ultimate interoperability: Eppie can communicate with Ethereum, Bitcoin and more
📬 IMAP/SMTP compatible: connect to Gmail, Microsoft Outlook etc.
🦄 Proton Mail Authentication: Eppie is the first native desktop client capable of that
🔐 PGP encryption: stay safe even with conventional email
🤖 Local AI agents
NOTE: the project is early in development, not all of the features are publicly availabe
via @dcntr
#email#p2p
📩 Не пропускаем почту вместе с @GmailBot
Бот для уведомлений, быстрых действий и отправки почты с вашего Gmail ящика
Немного советов для удобства:
- СоблюдайтеInbox Zero(не пожалеете..)
- Настройте пересылку писем с других ваших ящиков на основной Gmail
- Отпишитесь от ненужных рассылок.. в конце то концов ._.
Inbox Zero - начал применять очень давно не замечая, позже узнал как это называется. На самом деле здесь ничего сложного, просто нужно следить за чистотой вкладки входящих.
Наверное многие уже давно пользуются им, даже в последней новости об обновлении 5.13 он упоминался, но надеюсь будет кому-то ещё в новинку.
#bot#email
💌EMAIL by the Digits
3.7 billion: Number of email accounts worldwide
269 billion: Emails sent daily in 2017
121: Number of emails the average office worker gets per day
6: Average seconds within which people reply to a work email
45%: Percentage of spam in email traffic
95: Percentage of spam that gets delivered
3.1%: Average click-through rate for emails in North America
1.2 billion: Number of Gmail users
70 million: Amount of emails that Slack likes to boast it has “saved the world from”
775%: Percent increase in emojis in emails from 2015–2016
43%: Percentage of people that check email in the bathroom
#FunFact#Email
🚀@PerspectiveIX
🌀 http://prs.pctvix.co/TelegramIX
📱Email & Mobile Notifications in Driving Loyalty
Generating more direct traffic to websites and apps is an important priority for publishers, with #email#newsletters a particularly favoured tactic for retaining subscribers but also for attracting new users. The Washington Post operates around 70 different newsletters & has found that recipients consume around three times as much content as those who don’t use email news. RI’s own data this year show that 42% of US digital subscribers have used one or more email newsletters in the last week compared with 35% in the UK but just 17% in Norway and 19% in Sweden. It is clear this is one area where Nordic publishers could learn a few tricks from the United States.
via The Reuters Institute.
🔗 Read more & download the RI's Digital News Report 2019 in yesterday's Pulse - don't forget to subscribe.
Country analysis for: 🇬🇧🇦🇹🇧🇪🇧🇬🇭🇷🇨🇿🇩🇰🇫🇮🇫🇷🇩🇪🇬🇷🇭🇺🇮🇪🇮🇹🇳🇱🇳🇴🇵🇱🇵🇹🇷🇴🇸🇰🇪🇸🇸🇪🇨🇭🇹🇷| 🇺🇸🇦🇷🇧🇷🇨🇦🇨🇱🇲🇽| 🇦🇺🇭🇰🇯🇵🇲🇾🇸🇬🇰🇷🇹🇼| 🇿🇦
🚀@PerspectiveIX