Что делать если нужно поставить какую-то 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
Regina Ip, Lawmaker, criticized that blaming the fire onto bamboo Scaffolding is using it as a scapegoat and to misdirection the public. She also went on saying that this saying isn’t responsible towards the victims and their families.
Facing so many criticism, Security Chief of Hong Kong had to change his opinion after 3 days, saying that 7/20 samples of the green mesh net does not meet the standards.
#HongKongFire#TaipoFire#宏福苑大火
Hong Kong Silence Operation Part 4: Controlling the Narrative
The Hong Kong Government seems to have a protocol to control narrative right from the start. Instead of stopping the fire and saving lives, finding a proper scapegoat was their first priority.
Nov 26, the very same day of the fire, Xinyan Huang, a scholar from China, blamed on the bamboo scaffolding for fire to spread rapidly. Major news outlets including CNN, BBC, Reuters, the Guardians all reported the fire based on his only opinion.
Nov 27, John Lee, the Chief Executive of Hong Kong, announced a plan to phrase out bamboo scaffolding in Hong Kong.
Although some news have changed their opinion on bamboo scaffolding later on, the discussion about the fire focused on bamboo scaffolding rather than collusive bidding and how the government was involved.
Up until now, no government officials are arrested or responsible and no policy has been changed.
#HongKongFire#TaipoFire#宏福苑火災
Hong Kong Government is running a Silence Operation to cover up the the #TaiPoFire. John Li, the Chief Executive of Hong Kong, announced that there would be a 1 social worker to follow each affected family. Instead of understanding their needs, victims complain that they are actually being monitored. Some also said they received phone called twice a day telling them not to missed the election, an agenda that the government want to push so that it looks like they this rigged election is supported by the public.
香港政府正進行一項「Silence Operation」來壓制公眾聲音,掩蓋 #TaiPoFire 大埔火災事件。香港行政長官李家超宣布,每個受影響家庭將有一名社工跟進。但受害者投訴,這些社工並非了解他們的需求,而是實際上在監視他們。有些人還表示,每天收到兩次電話,提醒他們不要錯過選舉,這是政府想推動的議程,好讓這場操縱的選舉看起來獲得公眾支持。
#HongKongFire#宏福苑大房
The memorial service in Toronto fill up the whole hall. However, people continue to enter the hall giving flowers and signing petition.
追悼宏福苑火災的多倫多追思會座無虛席,然而仍然有人持續進入會場獻花並簽署請願書。
#HongKongFire#TaipoFire#toronto#宏福苑大火
Silencing Operation Part 3:
Influencers and even pro-Beijing Commentator who criticized the government for the fire has their articles and posts taken down all because of obvious and unavoidable factors.
University’s also block the walls where students stick their banners to show gratitudes to the victims.
Opinions and gratitudes are treated as a kind of hate speech to the Hong Kong Government.
多名網紅及甚至親北京評論員因批評政府在 #宏福苑火災 事件上的處理,其文章及貼文均被刪除,一切皆因「不可抗力因素」。
大學亦封鎖牆壁,阻止學生張貼橫額以向受害者表達慰問。
意見及慰問均被香港政府視為一種仇恨言論。
#HongKongFire#TaiPoFire#NSL
Volunteers Continue to Get Arrested
Normally, you would think that the Police or Anti-Corruption would be arresting government officials or contractors who are related to the #taipofire, but under #CCP, it is quite the opposite. 2 volunteers are arrested. Kenneth Cheung, former Tuen Muen District Council, was arrested by #NationalSecurity Police for inciting hatred. He incited hatred by handling supplies for the victims.
Another female volunteer, known as Tsing, who had been handling supplies was also arrested.
This is how the Hong Kong Government handle this tragedy. They want all the victims and those who help them to be silence.
#HongKongFire#宏福苑大火
Hong Kong Silence Operation Part 2
Numerous people who spoke out about their opinions about the #HongKongFire are arrested to intimidate everyone from criticizing the government.
On Dec 9, On-yin Wong, former Civil Human Rights Front deputy convener, was arrested. He expressed that the government should be responsible for the fire on YouTube.
On the same day, Gao Yu, award winning independent journalist was also interrogated by National Security Police.
Before them, Miles Kwan was arrested for initiating a petition, and 2 volunteers who organized supplies were also arrested. on Nov 30.
多名就 #宏福菀火災 事件發表意見的人士被捕,此舉旨在恐嚇公眾勿批評政府。
12月9日,前民陣副召集人黃安然被捕。他曾在 YouTube 上表示,政府應對火災負起責任。
同日,獲獎獨立記者高瑜亦遭國家安全警方盤問。
在此之前,關兆倫因發起聯署而被捕,另外兩名組織物資的義工亦於11月30日被捕。
#HongKongFire#TaipoFire#宏福苑大房
Hong Kong diaspora around the world gather together to raise their concerns for the #TaipoFire. Since the #HongKong government are silencing people from questioning, and disbanding volunteers, people outside of Hong Kong hope to speak out for them and tell the world about that this fire wasn’t caused by bamboo scaffolding but corruptions in Hong Kong.
流氓海外嘅香港人冇忘記到香港。喺世界各地唔同嘅地方度集會聲援 #宏福苑大火! 希望話俾全世界聽呢一場災難唔係一場意外,而係因為違標同香港政府嘅腐敗導致到咁多人嚟難。
#HongKongFire#宏福苑#宏福苑火災