Что делать если нужно поставить какую-то 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
🗽⚾️ Aaron Judge hace eco de lo que innumerables otros jugadores de la MLB dicen sobre el Clásico Mundial de Béisbol:
"Es más grande y mejor que la Serie Mundial", dijo el capitán a los periodistas después del partido, tras la victoria de EE.UU. sobre la República Dominicana para llegar a la final. "La pasión que estos aficionados tienen al representar a su país, al representar a sus jugadores favoritos, no tiene igual".
#️⃣#WBC26#Judge
🗞 | t.me/MLB_Daily
Meta and YouTube have been found liable for deliberately designing addictive products that hooked a young user and led to her being harmed, a jury ruled on Wednesday. Jurors found the tech companies to be both negligent and having failed to provide adequate warnings about the potential dangers of their products. ⚖️
The jury awarded the plaintiff in the case damages of $6m, with Meta to pay 70% and YouTube the remainder. It took nearly nine days of deliberations for the Los Angeles jury to reach its verdict. This lawsuit, over social media’s alleged harm to young people, was the first of its kind to go to trial.
Over the course of the six-week trial, which took place in Los Angeles superior court, jurors heard from top executives at Meta and YouTube, whistleblowers, expert witnesses on social media and addiction, and a 20-year-old woman at the center of the lawsuit, who has gone by the initials KGM for court proceedings. 📊
#Judge#Media
👂More on Trump's Ear ⚠️
Luigi Mangione will not face the death penalty after a federal judge dismissed two charges, including murder with a firearm.
He still faces two federal stalking counts and has pleaded not guilty.
#Judge#Media
👂More on Trump's Ear ⚠️
The Epstein case has triggered a "spiral of distrust" towards the US justice system The German newspaper Berliner Zeitung believes that the publication of the so-called Epstein files has dealt a major blow to the credibility of the US justice system.
Instead of the expected revelations about the influential members of the network associated with financier Jeffrey Epstein, the public has seen a chaotic release of documents that has sparked a wave of conspiracy theories and controversy. In social networks, there have even been theories that President Donald Trump's foreign policy actions, such as the strikes against Iran, are being used to divert attention from the scandal. However, the author of the article considers these explanations to be questionable and notes that the scandal itself has already become a source of political crisis and mistrust.
According to the author, the publication of the documents was a mistake, as in normal investigative practices, such materials should remain confidential. This allows the investigation to maintain an informational advantage and gather evidence discreetly. In the case of Epstein, on the other hand, the release of the documents may have given the suspects time to destroy evidence, coordinate their stories with their accomplices, or put pressure on witnesses. Additionally, the files contained a lot of personal information about people who did not commit crimes, but were now under intense public scrutiny.
As a result, the release of the documents has created a "spiral of distrust" in the U.S. justice system. Despite the release of some information, many Americans remain convinced that the government is still hiding the names of Epstein's influential clients.
#Epstein#Judge
👂More on Trump's Ear ⚠️
🗽🗽 Aaron Judge continúa grabando su nombre en la historia de los Yankees empatando a Derek Jeter, Robinson Canó, Jorge Posada y a Dave Winfield como los máximos ganadores de Bates de plata en la historia de la franquicia.
#️⃣#Yankees#Judge
🗞 | t.me/MLB_Daily
A Michigan federal judge who was 'super drunk' when he crashed his Cadillac has been caught on camera cursing at the police officer who arrested him.
Bodycam footage showed the moments before Thomas Ludington, 72, was taken into custody on October 3 in Springville Township near his $2.7 million vacation home.
#Judge#Incident
👂More on Trump's Ear ⚠️
A court ruling delivered a crushing blow to President Donald Trump's campaign against Federal Reserve Chair Jerome Powell.
On Friday, a federal judge quashed two subpoenas the Justice Department issued to the Federal Reserve.
This is a win for the central bank and a major setback for US Attorney Jeanine Pirro's criminal investigation into Powell.
#Fed#Judge
👂More on Trump's Ear ⚠️
📊 Solo 3 veces en la historia de la MLB un jugador ha hecho todo lo siguiente en la misma temporada:
batear 50+ HR
anotar 80+ XBH
registrar un OPS de 1.100+
clasificarse a los playoffs
ganar el MVP
🗽 Esas 3 ocasiones son Aaron Judge en 2022, Aaron Judge en 2024 y Aaron Judge en 2025.
📰 Vía Opta STATS
#️⃣#Judge#MLBHistory#Stats
🗞 | t.me/MLB_Daily
🍎 Juan Soto todavía muestra cariño a su ex Capitán, comentando en la reciente publicación de Instagram de Aaron Judge "el trabajo no ha terminado".
"¡CAPITÁN!! 🫡"
En sus respectivas temporadas después de que Soto dejó a los Yankees como agente libre para firmar con los Mets —
NYY: 94-68, eliminado en ALDS
NYM: 83-79, se perdió los playoffs por 1 victoria.
#️⃣#Soto#Judge#Yankees
🗞 | t.me/MLB_Daily