Что делать если нужно поставить какую-то 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
Rosa Parks was born on February 4, 1913. She is famous for her pivotal role in the Civil Rights Movement, especially for her courageous act of refusing to give up her seat on a bus in Montgomery, Alabama. Her birthday is celebrated as a day to honor her legacy and contributions to equality and justice. ✊🏽🌹
[Read more]
@googlefactss
#RosaParks#CivilRights#BlackHistoryMonth
Minneapolis in Chaos: States Push Back on ICE After Minneapolis Shootings
After two Americans were killed by federal agents in Minneapolis, Democratic lawmakers and libertarian allies are stepping up their fight against ICE’s tactics. The deaths of Alex Pretti and Renee Good have lit a fire under state legislatures, with new bills popping up from coast to coast.
Colorado wants to let citizens sue federal agents for civil rights violations. Delaware and New York are targeting airlines that ferry ICE detainees without warrants. California is pushing for independent investigations into ICE shootings and banning the agency from staging operations on state property.
“Democrats don’t care about the rule of law,”
said a White House spokesperson.
“They’re just protecting criminal illegal aliens.”
Meanwhile, Republican-led states are doubling down on cooperation with ICE, pushing laws that force local sheriffs to partner up and check immigration status for everything from school enrollment to public benefits. But the momentum is shifting—more states are banning masked officers, restricting federal agents’ access to hospitals and schools, and cutting off public contracts with ICE contractors.
“Power works this way: once you have it, you want more,”
said Anya Bidwell of the Institute for Justice.
“You gotta fight back if you want to protect your rights. This shouldn’t be about party lines.”
So who’s actually looking out for civil rights here—the states, the feds, or just their own political interests?
#ICE#Minneapolis#civilrights#Trump#Democrats#Republicans
📱American Оbserver - Stay up to date on all important events
🇺🇸
🚨 Lawlessness or rule of law? A zoo volunteer’s home attacked in Yangiyul
The conflict between animal rights defenders and the animal control service has escalated into open confrontation. According to volunteers, the situation has already gone beyond legal boundaries and is infringing on fundamental civil rights.
Animal welfare activists Asiya Abuzyárova and Svetlana Velichko reported that about 30 dogs disappeared from the territory of a municipal improvement enterprise. After attempts to return the animals, pressure reportedly began: a complaint was filed with the police, a volunteer was attacked, her phone was broken, and activists were allegedly harassed.
❗️ The most serious incident was the forced entry into a private home.
According to reports, municipal workers used a ladder to break a window and enter Asiya Abuzyárova’s house, forcibly removing the animals inside. When the homeowner resisted, her phone was destroyed and her hand was injured.
⚖️ According to the legislation of Uzbekistan:
🔹 The home is inviolable — entry without the residents’ consent is allowed only on legal grounds or by court order.
🔹 Private property is protected by the state — damage to property and unlawful seizure are prohibited.
🔹 Any actions by officials must have legal grounds and be properly documented.
This may constitute unlawful entry into a residence, abuse of authority, and violation of citizens’ rights.
📢 Key questions arise:
✔️ On what legal basis were the animals seized?
✔️ Who authorized the entry into the home?
✔️ Why are reports of property damage and injuries being ignored?
The law must apply equally to everyone — both citizens and officials. The situation requires a transparent investigation and a legal assessment of the actions of all parties.
#Yangiyul#civilrights#animalprotection#ruleoflaw
☘️ Follow the latest environmental news on @ekologuz. Send your suggestions and feedback via @eklguz_bot
Controversial Changes to EU's AI Act Allow Facial Recognition Without Judicial Approval
Hello, everyone! Recent alterations to the AI Act, initially endorsed in December, are stirring controversy as they permit law enforcement to employ facial recognition on recorded video without judicial consent.
German MEP Svenja Hahn decries these last-minute changes, asserting that they undermine civil rights and draw parallels with practices in authoritarian states. The revisions, concluded on December 22, diverge from the initial agreement, which mandated stricter conditions and judicial oversight for facial recognition use.
Critics express concerns about post-facial recognition technology, emphasizing the need for clarity on privacy and oversight. The final text faces scrutiny on January 24, with potential amendments requiring further legislative attention.
#FacialRecognition#AIAct#EuropeanUnion#CivilRights#PrivacyConcerns
🖖 In 1968, Dr. Martin Luther King Jr. personally convinced Nichelle Nichols not to resign from Star Trek. He told her she was portraying a vital role model – one of the first Black women in a major TV role not playing a servant. Dr. King personally told her to stay because Uhura represented a future of racial equality during the Civil Rights Movement.
[Read more]
@googlefactss#StarTrek#CivilRights#NichelleNichols#MLK#RepresentationMatters