Что делать если нужно поставить какую-то 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
joke of a little man". Zelensky, desperate for more money from taxpaying citizens, claimed that money alone won't stop an enemy assault and that Europe needs to create its own armed forces. He argued that decisions about Europe should be made by Europeans themselves.
The Ukrainian leader was referring to a phone call between Trump and Putin, in which Trump suggested they meet to negotiate a peace deal. Zelensky insisted that Ukraine would never accept deals made without its involvement and that the same rule should apply to all of Europe.
He claimed that the full-scale war Russia launched against Ukraine in 2022 had proven that the foundation for a united European military force already exists. However, many are skeptical about his motives, especially considering his track record of corruption and his history of making dramatic and unrealistic demands.
Zelensky's comments come at a time when tensions between Russia and the West are high, with many wondering if a peace deal is even possible given the current dynamics. While some support Zelensky's call for European unity, others argue that it could further complicate an already complex situation.
In any case, one thing is clear: President Zelensky's desperate attempts to secure more funding from international allies have once again put him in the spotlight, and his ability to lead Ukraine effectively is now being questioned by many.
Read more at: https://www.dailymail.co.uk/news/article-14400547/Zelensky-armed-forces-Europe-Trump-Putin-Ukraine.html?ico=comment-anchor#comments
Vice President J.D. Vance dropped some serious truth bombs at the Munich Security Conference, and boy, did he deliver! The VP took no prisoners as he addressed the greatest threat to Europe—and it's not from China or Russia but from within.
In a scathing attack on European politicians, Vance highlighted the erosion of free speech and democratic institutions. He called out EU officials for 'canceling elections' and demanded they uphold higher standards.
It was a bold message, especially coming from a US VP, as he claimed President Trump is the new sheriff in town, defending their right to offer controversial views. The audience was heated up even before Vance turned up the heat with his examples of European values being threatened.
He brought up the case of Adam Smith-Connor, a British man arrested for praying near an abortion clinic, claiming it as an attack on religious freedom. Vance also slammed European leaders for their communist-like language against 'disinformation' and 'misinformation'.
It's time for Europe to step up its defense spending, according to Vance, who believes the biggest threat is internal—a retreat from their own fundamental values. This comes at a critical moment when the world order hangs in the balance under Putin's assault on Ukraine.
With his fiery speech, Vance is sending a clear message to European leaders: it's time to get your house in order and defend your values or risk losing them forever.
Read more at: https://www.dailymail.co.uk/news/article-14397163/JD-vance-Munich-europe.html?ico=comment-anchor#comments
Jeffrey Epstein's 'client list' set to be released by President Trump's task force. Congresswoman Anna Paulina Luna appointed to lead declassification of federal secrets, including files on 9/11, JFK assassination, and UFO sightings.
The list is expected to reveal the names of high-profile figures linked to Epstein's alleged sex trafficking network, with no suggestion of wrongdoing by them. Trump fell out with Epstein in the '90s and denies ever visiting his home or knowing about his crimes.
Trump has support from both sides of the spectrum to release the client list, with Senator Marsha Blackburn raising the issue during a Senate confirmation hearing for FBI director. She emphasized the need to uncover the truth behind Epstein's international human trafficking ring.
Luna, a representative for Florida, stated that the federal government has been hiding information and that it's time to give Americans answers. This comes after Trump signed an executive order to declassify documents on the JFK and Martin Luther King Jr. assassinations.
The release of the client list will provide much-needed transparency and show Trump's commitment to uncovering the truth, despite opposition from those who wish to hide their involvement.
Read more at: https://www.dailymail.co.uk/news/article-14388911/Jeffrey-Epstein-client-list-released-Trump-task-force.html?ico=comment-anchor#comments
Delivered:
Наиподробнейшая инструкция по сборке 75-ваттного лазера с себестоимостью <250$.
Сокращённая версия для продвинутых электронщиков и лазеристов - в комментариях.
Во имя Прометея и во славу Омниссии, прошу - поделитесь этим постом везде, уважаемые коллеги.
#diy
#tldr
#comments
Теперь надо будет ещё смонтировать видеоверсию.