Что делать если нужно поставить какую-то 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
🏭Bali reduces dependence on Java: the island will build its own power plants
📰 Bali is on the verge of energy independence: the authorities are launching several projects to build their own power plants. Gas stations in Denpasar and Gianyar, as well as two new units on the north coast, will provide the island with 1.5 GW of power by 2029.
ℹ️ This will make it possible to abandon vulnerable underwater cables from Java and eliminate the risk of large-scale blackouts. Residents are being urged to support the initiative by installing solar panels and switching to renewable energy sources.
#development@BaliNews
📰The popular Android developer, Xaxtix, parted ways with Telegram.
In the release of the latest versions of Telegram Android, we find that Ilya Samorodov is no longer active in the development of Telegram.
Read more on iDubTG
#Development
👉The TG Times
🔖 On Long Term Software Development - Bert Hubert's writings #pinboard#development
https://berthub.eu/articles/posts/on-long-term-software-development/
🎰Bali governor rejects casino construction despite promised 100 trillion rupiah
📰 Bali Governor Wayan Koster has stated that he rejects the proposal to create a legalized casino, even despite the potential profit of 100 trillion rupiah.
🛕 According to him, the refusal is dictated by the principles of cultural tourism development, on which the island's economy is based.
🤔 At the same time, according to some analysts, the location of casinos in new areas, for example, near the northern airport under construction, could accelerate the development of these territories. And if it later turns out that casinos really do interfere with cultural tourism, they can always be closed.
#places#development@BaliNews
🌊Bali will build a kilometer-long promenade from Changgu to Cemagi
📰 A kilometer-long promenade will appear along the coast between Canggu and Cemagi by 2026. It will rehabilitate the eroded shoreline, create a wide pedestrian path and recreational areas.
📍 The cultural center will be the area near the Batu Ngaus temple, where a stage for kechak dances is planned. Traders will be distributed among the new pavilions to make the beaches convenient for both visitors and entrepreneurs.
#places#development@BaliNews
🏭The largest battery production project in Indonesia has begun
📰 Contemporary Amperex Technology Co. Limited (CATL), the world's largest manufacturer of batteries for electric vehicles, has begun a large-scale project in Indonesia to create production facilities and an ecosystem related to the production of electric vehicles.
🧲 The investment is estimated at $6 billion.
ℹ️ According to Indonesian Minister of Energy and Mineral Resources Bahliola Lahadalia, this is the first project of its kind and scale in the world. The launch of electric vehicle battery production is one of 18 large-scale industrial projects planned for implementation in Indonesia in the coming years. Together, they are estimated to be worth nearly $45 billion.
The projects will be implemented in the areas of nickel and bauxite production, as well as gasification, oil refining, and the creation of oil storage facilities. Some of the initiatives will affect fishing, agriculture, and the forestry industry.
#business#development@BaliNews
http://astrocodeschool.com/
Astro Code School is respected by tech firms and universities for a reason: we’re founded and staffed by a leading #web#development firm, Caktus Group. Our team interacts daily with the inner workings of Caktus so we see the trends and best practices that will make you job ready. If you’re prepared to launch a new career with the real-world technical depth employers seek, Astro is right for you.
Errors in Go:
From denial to acceptance
Learn how to stop worrying and love error handling in Go. Author of Overmind and imgproxy describes his journey through all five stages of Kübler-Ross model—from denial to acceptance—as he went deeper into the language, and shares his favorite patterns for dealing with errors in Go code.
#development#language
https://evilmartians.com/chronicles/errors-in-go-from-denial-to-acceptance
Ok, I’m online again so Happy New Year for everyone 🎈
The first article that I want to share this year is about channels design in GoLang, their structure and internal operations. Enjoy the reading!
#development#language
https://codeburst.io/diving-deep-into-the-golang-channels-549fd4ed21a8
Hello, there! One GoLang feature proposal about immutability is here 🙂
It’s a really interesting idea with pros and cons inside, it has a good explanation, use cases and examples for the following proposed changes: fields, arguments, variables, return values, methods reference types (Pointers, slices, maps, channels). This approach merits attention if you are interested in paths of GoLang development, so, have a good reading! 😉
#language#development
https://github.com/romshark/Go-1-2-Proposal---Immutability
“Should I Rust, or Should I Go” - this is an article with a quick comparison of Golang and Rust code styles, features and conveniences of usage.
#language#development
https://codeburst.io/should-i-rust-or-should-i-go-59a298e00ea9
Good day 👋 I would like to share following 7 advices in short article by Kartik Khare how to increase your code quality in GoLang. Of course, before using it you should understand reasons for each advice in the post. As example Kartik writes:
#6 Use int as keys instead of strings in Map.
It’s a good way but here we can get optimization for optimization 🤔
#development#language
https://codeburst.io/how-to-optimise-your-go-code-c6b27d4f1452