Что делать если нужно поставить какую-то 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 Smartphones With the Longest-Lasting Batteries
Every #smartphone users know the dilemma: It doesn’t matter how great your latest-generation smartphone is or which cutting-edge features it contains - the device still runs on old-fashioned electricity it draws from its battery, often the weakest part of the phone. With the number of apps people use and time they spend on their smartphone increasing, battery woes are all too common - the prevalence of powerbanks and charging stations popping up in different places certainly tell that story.
🦅@PerspectiveIX
📖 Read more on Statista.
🤝Support PerspectiveIX.
📱Smartphone Dominance
Following up on the poll above, although not producing the same results, here are some interesting stats from Pew Research Centre: #Smartphone users are now more likely to go online using their mobile phone than with some other type of device.
For smartphone owners, their mobile devices now outpace more traditional means of accessing the web. 46% of them say when using the internet, they mostly do so on their phone. This represents a 12% increase from 2013 when 34% of these users said this.
At the same time, the share of smartphone users who say a desktop, laptop or tablet computer is their primary device for going online has fallen from 53% in 2013 to 30% today. Roughly a quarter of smartphone users say they equally use a cellphone or a desktop, laptop or tablet computer when going online, up from 12% six years prior.
🚀@PerspectiveIX
🔈Smart Assistants Usages
According to GlobalWebIndex, that functional activities are the leading use case for #Smartphone voice assistant, like asking for directions or for checking the weather.
Home assistants, on the other hand, provide a more relaxing and interactive experience. The research also revealed that home assistant users perform a greater variety of behaviors on average, with an emphasis on content and entertainment, like streaming #Music.
🚀@PerspectiveIX via GlobalWebIndex.
❓ In the past month, have you used any Voice Assistants, such as Siri, Cortana, Alexa?
💥XIAOMI Poco C75 - Smartphone de 8+256GB
Potencia y estilo en tus manos
✅OFERTA: 98.0€
❌ Antes: 151.9€
💰Ahorras un 35%🔥
Disfruta de una pantalla fluida y cámaras de alta calidad para capturar tus mome
👉 Renueva tu smartphone ahora
#xiaomi#smartphone#tecnologia#descuentos#ofertas#viral#rebajas
🛰️Oferta publicada en Tecnología
📱Have We Reached Peak Smartphone?
After a decade of growth, the global #smartphone market came to a standstill in 2017. According to latest estimates from market research firm IDC, a worldwide total of 1,472 million #smartphones were shipped in 2017, virtually unchanged from the 1,473 million units shipped in the previous year.
🚀@PerspectiveIX
🌳https://prs.pctvix.co/2rBpZT1
Something is happening... in case it wasn’t clear...
#Smartphone#SmartWatch
🚀@PerspectiveIX
👻http://prs.pctvix.co/SnapchatIX
Do you own a Smart Watch?
👍 Yes
👎 No
📱Apple Regains the Global Best Selling Smartphone Spot
With the iPhone 8
According to Counterpoint’s Market Pulse, #Apple regained the top spot in the global best selling #smartphone list with the #iPhone 8. Seems like strong promotions (“How to shoot on iPhone”) running up to the FIFA World Cup helped the tech giant trigger buyer interest in Europe and other markets. iPhone 8 sales were steady in the US postpaid channels.
🚀@PerspectiveIX
📖 via CounterPoint: prs.pctvix.co/2zgwMrv
📑Q4 2018 Internet Report
The next billion doesn’t seem so far anymore!
Millions of people across Africa and South Asia came online for the first time in the past three months, with almost all of these new users accessing the #Internet solely via mobile devices.
- There are almost 4.2 billion internet users around the world in October 2018, up seven percent since this time last year.
- Around 3.4 billion people around the world used #SocialMedia in September 2018, up 10% since September 2017.
- More than 5.1 billion people now use a mobile phone, with most using a #smartphone.
🚀@PerspectiveIX via SlideShare (Slide Deck).