Что делать если нужно поставить какую-то 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
👀🍬 If you’ve been enjoying all that eye candy of the city's architecture on our feed recently, you have these five volunteers of ours to thank!
Hit play to find out what got them started on the #TexturesoftheCityexhibition, as well as how excellent architecture and design in Singapore continues to serve as inspiration for their craft! 📸
🤝 Interested to curate and present exhibitions at the Singapore City Gallery's City Canvas? Join us as a URA volunteer and get involved in shaping our city together with us! Other opportunities include building and remaking community spaces, leading community tours at the Singapore City Gallery, and more! Sign up at: go.gov.sg/uravp
🎉 Congratulations to our giveaway winners, Noorsyahidah and Rowell – instructions on how to claim your prizes are on their way to your inboxes! From now till 15 Oct, you can also treat yourself to a visual journey through the city at our #TexturesoftheCity exhibition, now on at the Singapore City Gallery.
Featuring stunning photography by URA volunteers, the free exhibition explores award-winning architecture around Singapore, while uncovering the innovative design innovations that have inspired fresh ways for us to live, work, play and move. 🤸♀️
📸☝ Tap in for a preview, and plan your visit at go.gov.sg/totc-exhb
Photo credits: Aaron Lai, Dennis Fajardo, Fallon Thng, Lawrence Pang, & Ng Wee Liang
[NOW ON AT THE SINGAPORE CITY GALLERY] Go on a visual journey through the city with five of our volunteer photographers at our latest #TexturesoftheCity photo exhibition!
From stunning captures of skyscrapers to school buildings, the exhibition showcases how good design plays an important role in unlocking even more possibilities in land-scarce Singapore.
☝ Explore how thoughtful design and architecture have inspired new ways in which we learn, work, and recharge, and plan your visit to the exhibition at: go.gov.sg/totc-exhb
📸 Photo credits: Ng Wee Liang, Dennis Fajardo, Aaron Lai, Lawrence Pang, and Fallon Thng
📢 [New exhibition to check out!]
See our city through a different light at our latest exhibition at the Singapore City Gallery! Unravel the #TexturesoftheCity through the lens of five of our volunteer photographers and discover how award-winning design has been thoughtfully weaved throughout our city to enable inspiring spaces that have changed the way we live, work, play, and move.
📸 Catch it at the Singapore City Gallery from now till 15 October 2022. Find out more at go.gov.sg/totc-exhb
Did you know that the Novena Church’s actual name is the Church of St Alphonsus? Since then, it’s become more popularly known as the Novena Church. The word “Novena” derives from "nine" in Latin, referring to the Catholic Church's nine days or weeks of devotion.
After being gazetted for conservation in 2011, the historic building was closed for substantial restoration work before reopening in 2017. The architecture of the structure is influenced by the Bible scriptures of King Solomon's temple, with a Gothic-inspired look that reflects the religion's early years. This historic landmark along Thomson Road remains a local landmark and community touchstone for all.
Swipe through to view more about its architectural details, and blessed Good Friday to all! 🧡
#texturesofthecity
Jurong Town Hall is a building that retained the zeitgeist of Singapore’s industrialisation and transformation. Constructed in 1974, this iconic building served as the headquarters of JTC until 2000, housing many visionary minds that worked to improve the lives of Singaporeans throughout our nation-building.
The winner of the 2018 Architectural Heritage Award has since been gazetted as a national monument and refurbished as a key landmark in Jurong – currently serving as a hub for trade associations. The building’s nautical elements are thought to be inspired by vessels at the Jurong Shipyard Corporation, giving the building the appearance of a ship’s hull with the clock tower as its mast.
Click through the pictures above to view more! #texturesofthecity
Happy Deepavali to all celebrating the Festival of Lights! 🪔
Today, we drop by Little India to discover some of the art within the historical district’s hidden spaces that not only pays homage to Hindu heritage and culture, but also celebrates our multicultural and multi-religious nation. Fun fact: Many of these pieces feature a contemporary twist by the artist to blend modern and traditional art forms.
Click through to check them out! Do you know of any other sculpture and murals in the area? 😀
#texturesofthecity
The 'lungs of the city' were what planners likened historic districts to when they proposed the conservation of these significant areas back in the 1980s. Ever wondered why this was so?
Find out as you explore today's #TexturesoftheCity feature inspired by the vibrant streetscapes of Little India!
Have you seen these #TexturesoftheCity?
This bold architectural feature connects two historic buildings in Singapore – both of which have been restored and elegantly transformed into a visual arts exhibition space. Can you guess where?
Have you seen these #texturesofthecity?
Besides a futuristic-looking facade, another notable feature found in this building's surrounding spaces is the use of vertical greenery.
Find out where!🔍
What does the neighbourhood of Bukit Pasoh have in common with pottery?
The area was once known for the trade of distinct earthenware pots, popular with the households living around the area, thus the name Bukit Pasoh was born.
Today, Bukit Pasoh is a modern mixed-use area that retains key elements of its past. If you walk along Neil Road, Bukit Pasoh Road, and Keong Saik Road, you’ll be able to spot many conserved clan associations, restaurants and bars that integrate their original shophouse exteriors with modern and chic interiors. Click through the pictures above for some highlights of the area!
If you enjoy exploring different neighbourhoods in Singapore, check out our newly launched “Love Local” book, created in partnership with Time Out: go.gov.sg/lovelocalguide. You can also head over to timeout.com/singapore/love-local to see more!
#architecture#TexturesoftheCity
#heritagebuildings#shophouses