Что делать если нужно поставить какую-то 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
今天蹭课的一个讨论问题:
Act in such a way that you treat humanity, whether in your own person or in the person of any other, never merely as a means to an end, but always at the same time as an end. (Kant)
Consider four reasons I might fail to cultivate my talents:
1. Idleness and indulgence
2. Working 100 hours per week in a cubicle as a high-paid analyst
3. Scrolling social media for 4 hours a day
4. “Earn to give" - forgoing a career as a physician so i can make more money to give to charity
Which (if any) treat myself as a means only and thus fail to respect my dignity?
#justice
Human rights activists complain about Lindsey Halligan.
Trump's former personal lawyer is Said to be Abusing his power
Human rights activists from the Campaign for Accountability filed a complaint against the acting Federal Prosecutor of the Eastern District of Virginia, Lindsey Halligan, at the Florida and Virginia Bar Associations. They claim that she violates professional ethics, lies and opens cases without sufficient grounds, ABC News reports.
#Trump#Justice
👂More on Trump's Ear
San Francisco sues Mars and Coca-Cola for excessive sugar, salt, and fat content in their products 🍬⚖️
San Francisco is suing food corporations Coca-Cola, PepsiCo, Kraft Heinz, Mondelez, W.K. Kellogg, and Mars for their heavily processed finished products.
In the lawsuit, Megapolis refers, among other things, to research by the World Health Organization (WHO), published in the medical journal The Lancet. 📚🌍
The ultra-processed products (UPF) of these companies often contain sugar, salt, fats, industrial starches, and additives such as emulsifiers, colorants, or flavors.
WHO warns that the consumption of such products increases the risk of cancer, cardiovascular diseases and diabetes. ⚠️🫀🍩
The San Francisco prosecutor's office accused the companies that the sale of harmful products led to the development of a crisis in the healthcare sector.
The city, in particular, is seeking a ban on "misleading" advertising of these products and is demanding financial compensation for the damage that, according to the prosecutor's office, was caused to San Francisco. 💼💵
The Manufacturers' Association has so far denied the charges. According to her, there is no universally recognized scientific definition of "ultra-processed foods," and calling products unhealthy just because they are processed is misleading consumers. 🏭🤷♂️
A similar case already occurred in the United States in the 1990s: then San Francisco sued the tobacco industry, and the case ended with the payment of compensation in the amount of 539 million dollars. 📜💰
#Health#Justice
👂More on Trump's Ear
Venezuela's highest court will review information submitted by electoral authorities and political parties to clarify the July 28 election results.
Read the report: https://venezuelanalysis.com/news/venezuela-presidential-candidates-and-political-parties-submit-electoral-evidence-to-supreme-court-far-right-opposition-rejects-request/
#Venezuela#Elections#Justice
⚖️🇺🇸LUXURY REAL ESTATE MOGULS CONVICTED OF SEX TRAFFICKING
🔹 Alexander brothers — Oren, Alon, and Tal — found guilty on 19 counts after five-week federal trial in NYC 🏛️👨⚖️
🔹 Over 60 women testified they were drugged and assaulted at Hamptons parties, Caribbean cruises, and Aspen ski trips 🏝️💊
🔹 Former Douglas Elliman brokers built billion-dollar Official real estate empire while running systematic predator scheme 🏢💰
🔹 Sentencing August 6, 2026 — brothers face life in prison as they remain jailed pending appeals 🔒⚡
Real estate world completely shattered — these weren't just millionaire playboys, they were calculated predators 😱🚨
#Justice#RealEstate
@america
On November 20, 1945, the Nuremberg Trials began, prosecuting Nazi war criminals for their actions during World War II. ⚖️🕊️
[Read more]
@googlefactss
#NurembergTrials#History#Justice
Ex-Judge Chernov’s Family Assets Seized by State
A court ruled Alexander Chernov’s (ex-Krasnodar judge, 1994-2019) activities illegal, confiscating family assets worth about 900 million rubles: 6 land plots, 106 commercial properties, 2 houses, 36 kg of gold, and 22 million rubles. Chernov secretly managed businesses; his ex-wife and daughters helped hide assets and re-register ownership. Former arbitration judge Anastasia Shepel is also implicated.
#Russia#Krasnodar#Corruption#Justice
The main news of Russia and the world ishere.
Plato’s Republic is an iconic philosophical masterpiece! Follow Socrates and friends on their exploration of justice, exploring questions such as
"What is justice?" and "What makes a government just?".
Experience philosophy at it's finest with Plato's Republic! #Philosophy#Classic#Justice
@ninjasblog
Which Ethiopia Is Being Praised? Judicial Independence, Armed Conflict, and the Rule of Law in Contemporary Ethiopia. Read more.
https://borkena.com/2026/03/10/which-ethiopia-is-being-praised-judicial-independence-armed-conflict-and-the-rule-of-law-in-contemporary-ethiopia/#Ethiopia#politics#conflict#Justice#ruleoflaw
🚨🇺🇸FEDERAL JUDGE ORDERS REPATRIATION OF VENEZUELANS DEPORTED TO CECOT PRISON
🔹 US must allow Venezuelans to return from El Salvador's CECOT prison 🧑
🔹 Court rules deportation violated constitutional rights
🔹 130+ men held in notorious megaprison now eligible to fight cases
Landmark decision: "This situation would never have arisen had the Government simply afforded Plaintiffs their constitutional rights" — Judge James Boasberg.
#USNews#Trump#immigration#Venezuela#Justice
@america
Venezuelan President Nicolás Maduro tasked his new minister for penitentiary affairs with taking measures against corrupt practices in the legal system. Inmates in dozens of prisons suspended a hunger strike against judicial delays and poor incarceration conditions following the government's response.
Read the full report here: https://shorturl.at/t1g2l
#Venezuela#Justice#Prisons#legalsystem