Что делать если нужно поставить какую-то 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
📰Interior of Maserati restomod for 585 thousand euros revealed
🚘 Italian company Modena Automobiliannounced the creation of a restomod Maserati Biturbo Shamal in November last year. Visually it refers to a rare model Maserati Shamal, but as a donor involved more mass Maserati Biturbo. Now the first renderings of the exterior were published, and there are images of the interior, made in a deliberately analog style.
ℹ️ It generally repeats the original interior of the Maserati Biturbo – for example, the contours of the front panel and the center console were recreated. The equipment is promised to include Recaro Classic seats and climate control, a removable handheld chronometer will appear on the front panel, and acoustics can be chosen among the brands Bose, JBL or Alpine. The car will also have a rear sofa that is restored seats from the classic Maserati Biturbo.
@CarsNews
#Maserati#restomod
A Ferrari F355 from the 1990s has been transformed into a carbon fiber restomod, with the exterior design led by former Jaguar designer Ian Callum. The exterior panels of this restomod by Evoluto Automobili are crafted from carbon fiber. The interior can be customized with carbon fiber, suede, and other materials chosen by the client.
The restomod retains the stock 3.5-liter V8 engine from the F355, but the engine undergoes serious modifications. It is claimed to deliver 420 hp and is paired with a six-speed manual transmission.
A total of 55 units will be produced.🏎️💨
#FerrariF355#Restomod#Cars#Auto#LuxuryCars
Introducing the stunning European RS by Thorney Kelham, a reimagined classic Porsche 911 available for $750,000!
🚗 This project enhances the exterior and interior design, widens the track, upgrades the suspension, and installs carbon-ceramic brakes.
💥 The base engine is a 3.8-liter flat-six from the Porsche 911 (993), tuned to 390 hp. For a premium option, a 4.0-liter unit producing 406 hp is offered, with the top-tier 3.8-liter engine spinning up to 10,000 rpm.
🏁 Only 25 units will be crafted! Get your hands on this masterpiece now!
🔥#ThorneyKelham#EuropeanRS#Porsche911#Restomod#LuxuryCars#Auto
🚗✨ Introducing the stunning restomod Jaguar XK120, designed by former McLaren designer Paul Howse! 🌟
With a starting price of £550,000 (over $720,000), only 25 exclusive units will be produced. Each European GT features a lightweight alloy body, giving it a wider and lower stance than the original.
Under the hood, the iconic 3.8L inline-six engine has been completely reimagined, delivering an impressive 300 or 340 horsepower—up from the original 220 hp! 💪🔥
#JaguarXK120#Restomod#EuropeanGT#PaulHowse#LuxuryCars#CarEnthusiasts#Auto🚘
🚗✨ Introducing the Veloce12: A Stunning Restomod of the Ferrari 550 Maranello! ✨🚗
For €690,000, Touring Superleggera has reimagined the iconic 550 Maranello into the breathtaking Veloce12! 😍
🔍 Key Features:
- Custom Carbon Fiber Body: Crafted from scratch for a lightweight and sleek design.
- Modern Lighting: Upgraded LED headlights and taillights for a contemporary touch. 💡
- Revamped Interior: A complete redesign that maintains the classic essence of the original. 🛋️
💥 Power Upgrade:
The atmospheric V12 now boasts an impressive 510 hp (up from 485 hp) with enhanced cooling and a custom exhaust system. 🔥
🛑 Performance Brakes: Equipped with powerful Brembo calipers for ultimate stopping power! 🚀
#Veloce12#Ferrari550#Restomod#TouringSuperleggera#CarEnthusiast#Supercar#LuxuryCars#Auto🚘💖
🚗✨ Restomod Magic: BMW 8 Series Reimagined! ✨🚗
Check out this stunning restomod of the first-generation BMW 8 Series! 🏎️💨
🔧 Upgrades Include:
- Carbon Fiber Panels: Lightweight and sleek! 🖤
- Powerful V10 Engine: Swapped from the BMW M5 (E60) and bored out to 5.8 liters! 💥
- Modern Interior Touches: Blending classic with contemporary! 🛋️
#BMW#Restomod#8Series#M5#CarEnthusiast#ClassicMeetsModern#CarbonFiber#V10Power#Auto🚘💫
Just sold at auction! 🚗💰
This stunning Alfa Romeo 2000 GTV restomod with a carbon fiber body went for $220,000. 🤑
It took around four years to build this beauty, with everything from the chassis to the powertrain being completely overhauled.
🛠️ Italian specialists worked on the chassis and body, while the rest of the work was done in Canada. The upgraded 2.0 carbureted engine's exact output isn't specified, but the original Alfa Romeo 2000 GTV came with a 130-horsepower engine. 🏁
#AlfaRomeo#2000GTV#Restomod#CarbonFiber#Auction#ClassicCar#LuxuryCar#ItalianStyle🇮🇹
🚗💨Introducing the Doughboy: A Mind-Blowing Restomod with 2838 HP!💥
At the SEMA Show, we unveiled a beast that redefines power and performance! 🔥 This incredible V8 engine boasts a staggering 8.8 liters of displacement and is equipped with dual turbochargers, pushing the limits of automotive engineering. 💪✨
🔧 With the engine strategically shifted 40 cm back towards the center of the wheelbase, every detail has been meticulously crafted from scratch, including the intake, exhaust, and cooling systems. 🛠️
💎 Custom parts were expertly created using CNC machining and 3D printing technology, showcasing innovation at its finest.
Get ready to experience the future of restomods! 🚀
#Doughboy#SEMA2023#Restomod#V8Power#Turbocharged#CarEnthusiast#AutomotiveInnovation#CustomCars#CNC#Auto