Что делать если нужно поставить какую-то 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
Recently I’ve been reading sci-fi by qntm and had a blast. He’s probably most known for the novel There Is No Antimemetics Division which is a gem in a SCP setting. Highly recommended.
If you need some convincing, read this short story first: https://qntm.org/transi
P.S. Most of his works is freely available on his website.
#scifi
В фантастике часто встречается сюжет о сверхмощном компьютере, который обрабатывает внутри себя симуляцию мира (вселенной, планеты, города).
В 6-й серии 10-го Доктора Кто инопланетяне создают симуляцию Земли, чтобы понять, как её захватить. В сериале Devs герой делает виртуальную копию вселенной, чтобы знать всё прошлое и будущее. Нередко искусственный интеллект продумывает все варианты развития человечества, чтобы подсказывать людям лучший выбор (начиная от Мультивака Айзека Азимова и заканчивая третьим сезоном Westworld).
Порассуждал с точки зрения программиста о том, почему это, скорее всего, принципиально невозможно.
#scifi#dev
https://teletype.in/@clockstackwheels/computer-prediction
🍿 Coppola’s Epic Comeback: ‘Megalopolis’ Drops Stunning Final Trailer After Controversy
📆Release: September 23, 2024 (IMAX) · September 27 (Theaters)
🎭Genre: #SciFi · #Drama
🔥 After the uproar caused by the first trailer, which was pulled for using fake critic quotes, Francis Ford Coppola is back with a fresh trailer for Megalopolis—this time, free of drama! In this modern epic, Adam Driver plays Caesar, a visionary architect trying to rebuild New Rome 🌆 after a disaster, facing off against Mayor Cicero (Giancarlo Esposito), who defends a corrupt system. Nathalie Emmanuel, as Julia, the mayor’s daughter, is torn between love for Caesar and loyalty to her father ❤️⚔️.
With an all-star cast featuring Laurence Fishburne, Aubrey Plaza, and Shia LaBeouf, this trailer 🚀 resets expectations for Coppola’s decades-long passion project. 🎬 After its lukewarm reception at Cannes, the director aims to redeem his legacy with a visually stunning and ambitious film. 🌟
🍿 Project Hail Mary: Too Spoiler-Heavy to Be Epic?
📆Release: March 20, 2026
🎭Genre: #SciFi · #Comedy
🍿Follow movie
I’ll admit the trailer had me on the edge of my seat… until they showed Rocky and killed all the mystery. Ryan Gosling (‘Barbie’, ‘First Man’) is Ryland Grace, the reluctant science teacher turned astronaut tasked with saving our dying sun, and Sandra Hüller (‘Anatomy of a Fall’) is the voice of reason pushing him into the void
Directors Phil Lord and Christopher Miller (‘Spider-Man: Into the Spider-Verse’, ‘The Lego Movie’) deliver stunning visuals, but was it necessary to reveal the alien encounter so early? 😤 Some book fans call it “selfish” to lay out the twist, while others praise the clarity and Weir-style humor. To me, this marketing gamble is a high-wire act between surprise and spectacle. 🚀✨
🍿 'Mickey 17': Dying Over and Over for a Paycheck
📆Release: March 7, 2025
🎭Genre: #SciFi · #Thriller
It's hard to accept that 'Mickey 17' is becoming one of those inexplicable cases where quality and box-office success don't align. This film marks Bong Joon Ho's highly anticipated return following his monumental success with 'Parasite', which elevated him to cinematic greatness, earning four Oscars and a Palme d'Or.
This time, the South Korean genius blends the dark satire of 'Snowpiercer' with the sharp social and environmental commentary he explored in 'Okja', delivering a futuristic dystopia as amusing as it is thought-provoking.
👉 Continue reading here 🍿🌟
🍿 'Mickey 17': The Clone That Won't Quit and Dies Over and Over Again
📆Release: March 7, 2025
🎭Genre: #SciFi · #Thriller
I love how Mickey 17 blends the suffocating atmosphere of Moon with the dark humor of Snowpiercer. Robert Pattinson (The Lighthouse, Tenet) plays an "expendable" forced to die repeatedly while his boss prints new copies of him aboard a ship headed to a frozen planet. 💀🔁
How will Mark Ruffalo (Poor Things) fare in what seems like a villainous role? We'll also see Toni Collette and Steven Yeun embracing their wildest sides. Director Bong Joon Ho, the mastermind behind Parasite and Okja, dives back into his signature dark comedy vibe. On top of it all, Naomi Ackie (Star Wars: The Rise of Skywalker) adds a romantic touch to counterbalance the chaos.
Let's see if this adaptation can outdo the limitations of the original book and if the "Batman in space" vibe 🦇🚀 delivers memorable moments. Without a doubt, dying repeatedly has never looked so fun.
🍿 Predator: Badlands – The Predator’s got a makeover… and a heart?
📆Release: November 7, 2025
🎭Genre: #SciFi · #Action
🍿Follow Movie
Dan Trachtenberg (Prey, 10 Cloverfield Lane) returns to shake up the Predator universe once again. In Predator: Badlands, the tables turn — a young outcast Predator teams up with Thia, played by Elle Fanning (The Great, Super 8), on a hostile alien planet. Fanning pulls double duty, playing twin sisters — and one of them might be a Weyland-Yutani android 👁. The aesthetic is gritty, weirdly emotional, and yes, the Predator has main character energy (and a killer hairstyle). 😎
I’m intrigued by the bold direction, but here’s the question: does humanizing the Predator risk stripping away the fear that made him iconic? Or is this exactly the fresh angle the franchise needed to evolve past its own formula?
🍿 Venom: The Last Dance promises an epic farewell
📆Release: October 25, 2024
🎭Genre: #Action · #SciFi
🎬 The final chapter of Tom Hardy’s 'Venom' trilogy is almost here, and the last trailer teases an explosive conclusion. Eddie Brock and Venom face off against alien creatures led by Knull, the god of symbiotes, in a wild chase to Las Vegas. Yes, it's as crazy as it sounds! 🎰
With a comedic twist, Hardy and Venom take on Vegas in a hilarious, action-packed ride, closing a trilogy that’s balanced the grotesque with pure entertainment. The best part? A surprise Marvel villain awaits!
🍿 Venom: The Last Dance promises an epic farewell
📆Release: October 25, 2024
🎭Genre: #Action · #SciFi
🎬 The final chapter of Tom Hardy’s 'Venom' trilogy is almost here, and the last trailer teases an explosive conclusion. Eddie Brock and Venom face off against alien creatures led by Knull, the god of symbiotes, in a wild chase to Las Vegas. Yes, it's as crazy as it sounds! 🎰
With a comedic twist, Hardy and Venom take on Vegas in a hilarious, action-packed ride, closing a trilogy that’s balanced the grotesque with pure entertainment. The best part? A surprise Marvel villain awaits!
🍿 Farewell Venom! 'Venom: The Last Dance' Promises an Epic Finale
📆Premiere: October 25
🎭Genre: #Action · #SciFi
Tom Hardy bids farewell to Eddie Brock and his symbiote in 'Venom: The Last Dance,' the final installment of the trilogy. This last trailer shows Eddie and Venom on the run, facing a massive alien and government agents. Directed by Kelly Marcel, the film promises frenetic action and even a Venom-ized horse. The cast includes Juno Temple and Chiwetel Ejiofor. After the success of 'Venom' and 'Venom: Let There Be Carnage,' Sony is going all out to close this surprising box office hit with a bang. 🎬🚀
> 𝘴𝘦𝘳𝘪𝘦𝘴 · 🚀𝘣𝘰𝘰𝘴𝘵