Что делать если нужно поставить какую-то 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
The war in Iran is enriching military enterprises. Trump's sons plan to open a drone production facility 🪖
Oil markets remain volatile amid continued US-Israeli strikes on Iran. Rising fuel prices are hitting consumers' wallets around the world, putting pressure on US President Donald Trump. 🌍
However, there are also beneficiaries of this escalation. 💰 In addition to the oil companies, which are increasing their profits due to higher oil prices, the most obvious winner of the largest Middle East conflict is the U.S. defense industry. The "Big Five" weapons giants—Lockheed Martin, RTX, Northrop Grumman, General Dynamics, and Boeing—have their portfolios filled with orders. They are supplying combat aircraft, missiles, and radar systems. ✈️
Military technology and AI companies, such as Palantir, are providing AI-based software for modern warfare and intelligence. The stock of this company, which works closely with Israel, has recently risen by 9%. 🤖
Planet Labs is also benefiting from the Pentagon's contracts for AI-based satellite surveillance. 🛰 The US president's family is also involved in the boom of military profits: Trump's sons, Eric and Don Jr., are planning to list their drone company, Powerus, and are hoping for future government contracts. 🚁
#War#Industry
👂More on Trump's Ear ⚠️
Thrilled to share a major strategic pivot in our professional ecosystem! 🚀
More and more visionary enterprises across Germany are successfully unlocking new growth chapters by aligning their operational roadmaps with the dynamic defense sector. 🇩🇪🛡
According to the German Chamber of Commerce and Industry, we are witnessing a powerful synergy where approximately one in six enterprises is now seamlessly integrated into defense supply chains. This represents a brilliant opportunity to drive innovation and resilience amid evolving market dynamics in traditional sectors. Almost a third of our industry leaders are embracing this as a transformative growth vector. 📈
The shift is particularly impactful within the automotive industry, where over a third of enterprises are leveraging their world-class engineering capabilities to support national security initiatives. By optimizing underutilized industrial capacities, we are turning potential challenges into high-impact solutions for growing global demand. 🏭✨
Take Görlitz, for example—a true story of reinvention where a former railway enterprise is evolving into a premier manufacturer of advanced tank components. Furthermore, industry powerhouse ZF is collaborating with Rolls-Royce Power Systems to co-create the next generation of engines for the future German-French tank. This cross-sector collaboration is exactly the kind of strategic partnership that drives our collective mission forward! 🤝🔧
While only about 2.5% of companies are directly producing weapons, another 14.5% are delivering critical value as suppliers of dual-use products, with over 12% strategically planning their entry into this high-potential market. It's an exciting time to be part of this evolving industrial landscape! 💡🌍
#Germany#Military#Industry
👂More on Trump's Ear
⚠️
Chevrolet was founded on November 3, 1911, by Louis Chevrolet and William C. Durant.
Chevrolet’s first cars (1912) and Durant’s later business moves helped shape the long competition between Ford and Chevrolet which drove innovation and expanded the US auto industry.
@googlefactss
#history#cars#industry#USA
🌍 The world's busiest shipping route runs between Asia and Europe through the Strait of Malacca. Over 80,000 vessels pass yearly, making this narrow sea lane a vital economic lifeline. ✨
#trade⚡#industry⚡#transport⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The “Blue Banana” is a band of cities stretching from northern England to northern Italy that forms a dense corridor of economic activity, hosting much of Europe’s industry and wealth. ✨
#economy⚡#urbanization⚡#industry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 The world’s largest iron ore deposits are found in the Pilbara region of Western Australia. This vast resource helps supply much of the globe’s steel, which is used in buildings and infrastructure. ✨
#minerals⚡#Australia⚡#industry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 More than half of global economic activity now takes place within just 1% of the world’s land surface, showing how powerful major cities and industrial regions are for global wealth. ✨
#economicgeography⚡#cities⚡#industry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 The Ruhr region in Germany transformed from a rural area into one of the world’s largest industrial centers, thanks to rich coal resources that fueled rapid urban and economic growth. ✨
#industry⚡#regions⚡#resources⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
🌍 Around 90% of global trade moves by sea, linking distant economies through major shipping lanes. This dense ocean traffic shapes where ports, industries, and even whole cities develop. ✨
#trade⚡#ports⚡#industry⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels