Что делать если нужно поставить какую-то 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
⛳International Golf Day on 15 June
📍 Marriott International Corporation is holding its annual International Charity Golf Day in Bali. This year's event will be held on 15 June at the National Golf Club in Nusa Dua.
🏌️♀️ Everyone can join this elite and expensive game, not only through participation in tournaments, but also during the evening programme, which the organisers announce as a kind of networking.
🎷 The festive evening will take place at the Westin Resort Nusa Dua at 18:30 the same day. Everyone is welcome to attend. The dinner will feature a buffet of international cuisine with beer, wine and soft drinks. In addition, guests can expect door prizes, auctions, and an entertainment programme with live music.
@BaliNews
#wheretogo#events#NusaDua
🎾Tennis in Bali: Nusa Dua opens clubhouse for ATP level tournaments
📍 The Bali Golf and Racket Club has opened in Nusa Dua, ready to host ATP tournaments in the future. It is the newest sports complex located in the heart of one of Bali's most prestigious resort areas, The Nusa Dua, which is famous for its five-star hotels and unique infrastructure.
🏆 The club was the first of its kind on the entire island. With its appearance, Bali acquires the status of not only a paradise island, but also a center for international tennis tournaments and sports tourism.
@BaliNews
#goodnews#sport#NusaDua
🎶TGIF 2025 music festival will return to Bali in May
The event promises to be one of the highlights of the music season in Bali.
📆 May 24-25
📍 At a new venue in Port of Benoa
ℹ️ In addition to concerts and live music, guests can expect food courts from local businesses, photo zones, interactive entertainment and relaxation areas. Parking and shuttles to shuttle guests are available for convenience.
🎫 Tickets are on sale now: one-day, two-day and VIP packages are available on the official website from Rp 150.000.
#events#festivals#wheretogo#NusaDua@BaliNews
🛎The first Waldorf Astoria hotel opens in Bali: second attempt
📰 The Hilton hotel group is expanding its presence in Bali. Waldorf Astoria Bali will be located between the Hilton and Kempinski hotels in Nusa Dua, 14.5 km from Ngurah Rai International Airport. The hotel is scheduled to open in late 2027.
🏨 Waldorf Astoria Bali will include 71 spacious villas and 68 guest suites, as well as the standard infrastructure for a chain hotel — restaurants, a spa, a fitness center, children's entertainment, and event rooms.
ℹ️ Waldorf Astoria had already announced the opening of its hotel in Bali in 2014. At that time, the location was chosen near Pandawa Beach in the south of the island. The opening was planned for 2027, but something went wrong. The massive concrete unfinished building can still be seen on the cliff to the left of the entrance to Pandawa Beach.
#places#realestate#development#NusaDua@BaliNews
🚤New Bali water taxi service launches for tourists
📰 A new marine transportation service, Bali Marine Water Taxi, has been launched in the popular resort area of Benoa (Nusa Dua) in Bali.
📍 The tourist cab service connects the seaports of Tanjung Benoa, Serangan and Pedungan (South Denpasar).
35 minutes. That’s all it takes. No traffic, no stress - just ocean views and open horizons. Uluwatu is calling.
👍 This is just one of the many sea routes Bali plans to develop in the coming months.
@BaliNews
#goodnews#places#services#transport#tourism#NusaDua
🛣Details about the construction of a district road in Bukit
District authorities are set to solve the road issue in Uluwatu by laying a new district road.
Construction of the first section from Siligita village to Sawangan in Nusa Dua district has already started.
The original idea was to extend the toll road, which now runs from the airport to Nusa Dua, all the way to Uluwatu.
Right now, traffic on the main road jl. Uluwatu is difficult because it is both a hub of commerce and the main thoroughfare of the area, used by everyone from locals to construction vehicles and tour buses.
The land acquisition budget for 2024 will be $16 million, with the next one already promised to increase to $19 million.
According to an insider in Bali's land office, all consideration of new housing development in the green zone on Bukit is now halted just in time for the land acquisition for the new roads.
@BaliNews
#roads#roads#authorities#Bukit#Uluwatu#NusaDua