Что делать если нужно поставить какую-то 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
Rats are nocturnal and shy creatures that prefer to stay in small and dark spaces, making it challenging to track them down.
Apart from conducting rat surveillance at publicly accessible places islandwide, #NEAofficers also carry out risk-based checks at various known hotspots.
Check out the different types of equipment used to overcome challenges faced during inspections, and learn more here: https://fb.watch/laCn_dEdrY/
3 local cases of Zika virus infection have been confirmed in the Kovan area in the past month. Vector control operations have commenced in the vicinity.
As our #NEAofficers are conducting inspections and indoor spraying of insecticides, we urge residents to cooperate with them. Besides eliminating mosquito breeding habitats, those residing at Zika and dengue cluster areas should carry out ‘S-A-W’ actions:
- Spray insecticide in dark corners around the house
- Apply insect repellent regularly
- Wear long-sleeve tops & long pants
go.gov.sg/nea-zika-12may2023
Happy Labour Day!
Here’s a huge THANK YOU to all who are working hard to keep our nation running.
A special shout-out too to thank our cleaners for keeping our city clean and green, our hawkers for working tirelessly to provide delicious hawker fare, as well as #NEAofficers for ensuring a clean and sustainable environment.
#NEAOfficers like Sulaiman work with these waste collectors to ensure biohazardous waste will be collected and incinerated quickly, in a way that is safe for waste handlers and the environment during the COVID-19 period. Find out what he does on our Instagram story highlight at www.instagram.com/nea_sg!
#NEAOfficers prepared a surprise for our hawkers last week! 14,000 care packages will be distributed to our hawkers who have been working tirelessly so that we can continue to enjoy our favourite hawker food.
https://youtu.be/T_ArJhAOAHA
Beware litterbugs - your poorly discarded items could become the stink of the neighbourhood! Let’s avoid attracting unwanted smells and pests, by properly binning our rubbish. Together, we can #KeepSGClean!
Our #NEAofficers have been working hard to apprehend high-rise littering offenders, using data analytics to prioritise camera deployment. As high-rise littering cases are usually harder to detect, they may take some time to be resolved.
If you witness such incidents, do take note of specific details such as date, time and precise location (block stack or column), and include them when submitting feedback (www.nea.gov.sg/feedback), to help with our investigation.
#DidYouKnow that there are 3 main rat species found in Singapore? From roof rat to sewer rat to house mouse, find out how our #NEAofficers carry out rat surveillance and look for signs of rat activity during their inspections, and get useful tips on rat prevention measures: https://fb.watch/laCn_dEdrY/
#SGDengueUpdate Over 2,700 dengue cases have been reported in 2021. Increasing Aedes aegypti mosquito population, and higher circulation of less common Dengue virus serotypes 3 and 4 to which we have lower population immunity, contribute to higher risk of dengue transmission. While our #NEAOfficers continue to conduct targeted inspections at areas with higher mosquito population, and step up operations at dengue cluster areas, residents should do the #MozzieWipeout regularly to #BLOCKDengue. https://go.gov.sg/nea-dengue-1jun2021
Where there are wet and dark crevices, NEA’s Dengue Inspection Officer Marthandan will be there. Let him show you how he and his team spot and tackle mosquito breeding in the areas around you!
Join him in our #NEAOfficers Story Highlight on our Instagram profile (www.instagram.com/nea_sg)!
#SGUnited#SGTogether
Whenever NEA receives feedback on noise or smell nuisance, #NEAofficers such as Joey would investigate the root cause and try to resolve the issues for residents. Read on to find out more about his winning formula: https://www.facebook.com/NEASingapore/posts/324902236450865
#PeopleofNEA#NEA20
#InNEAvation#DidYouKnow the COVID-19 virus can be detected in human stools? Read about the novel wastewater surveillance method initiated by #NEAScientists early last year. https://go.gov.sg/wastewatersurveillancepaper
#FightCOVID19#NEAOfficers