Что делать если нужно поставить какую-то 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
#POWELL
- ECONOMY IS STRONG
- INFLATION HAS EASED SUBSTANTIALLY
- IN NEAR TERM ELECTION WILL HAVE NO EFFECT ON POLICY DECISION
- ECONOMY HARD TO FORECAST BEYOND NEAR TERM
-SAYS HE WOULD NOT RESIGN IF ASKED TO
- NOT GOING TO TALK ABOUT ANYTHING RELATING TO ELECTION
- NOT PERMITTED UNDER THE LAW TO DEMOTE A FED CHAIR
-RAISING RATES IS NOT OUR PLAN
👇Join the VIP family today👇
Message: t.me/FUTUREEXPERTADMIN
The head of the Federal Reserve System, Jerome Powell, made a video message in which he accused the president of exerting pressure on the Fed through a threat to open a criminal case.
#Fed#Powell
👂More on Trump's Ear
🏦📊FED DELAYS MARCH RATE DECISION AS INFLATION CONCERNS RESURFACE
🔹 Federal Reserve pushes back planned March rate cut citing "persistent core inflation above target" at 3.2% 📈
🔹 Powell signals cautious approach: "Data dependency remains paramount" as housing costs surge 15% annually 🏠
🔹 Wall Street reacts negatively: Dow drops 340 points, tech stocks tumble on higher-for-longer rate outlook 📉
🔹 Consumer spending shows resilience despite credit card delinquencies hitting 8-year high of 4.6% 💳
Markets betting on single rate cut by December instead of aggressive spring easing cycle originally expected 📅
#Fed#interestrates#inflation#Powell#economy
@america
Global Central Banks Booed Trump for His Threats Against Powell
Global central banks have issued an extraordinary joint statement offering “full solidarity” to the US Federal Reserve chair, Jerome Powell, in the face of the latest threat to his independence from Donald Trump’s White House.
“The independence of central banks is a cornerstone of price, financial and economic stability in the interest of the citizens that we serve. It is therefore critical to preserve that independence, with full respect for the rule of law and democratic accountability,” the statement said.
It was signed by nine central bank governors including the Bank of England governor, Andrew Bailey, and the chair of the European Central Bank, Christine Lagarde.
It was coordinated by the Basel-based Bank for International Settlements, which added its chair and general manager to the signatories.
Other signatories to the unprecedented statement include the central bank governors of Australia, Sweden, Denmark, Switzerland, Brazil, South Korea and Canada. More names are expected to be added later on Tuesday.
They pay testament to Powell’s “integrity” and “unwavering commitment to the public interest”, calling him a “respected colleague who is held in the highest regard by all who have worked with him”.
Trump has repeatedly criticised Powell, whom he appointed in 2018, for failing to cut interest rates fast enough.
But the clash between the two men took a dramatic turn earlier this week when Powell issued a strongly worded video statement, saying he was being prosecuted by the US Department of Justice.
He said he had been singled out because the Fed’s policymaking board had set interest rates “based on our best assessment of what will serve the public, rather than following the preferences of the president”.
Trump has moved to distance himself from the investigation, however, claiming he was unaware of it. “I don’t know anything about it,” he told NBC News.
Powell is due to step down as chair of the Fed board in May, and Trump is expected to announce his successor in the coming weeks.
The former Fed chairs Alan Greenspan, Ben Bernanke and Janet Yellen had already condemned the threat to Powell on Monday, saying the move could have “highly negative consequences”.
“This is how monetary policy is made in emerging markets with weak institutions, with highly negative consequences for inflation and the functioning of their economies more broadly,” their statement said.
#trump#central#banks#threats#powell
📱American Оbserver - Stay up to date on all important events
🇺🇸
Federal Reserve Chair Jerome Powell Faces a Stiff Challenge
Justice department opens investigation into Jerome Powell as Trump ramps up campaign against Federal Reserve.
The independence and credibility of America’s central bank is under threat after the Department of Justice opened a criminal investigation into Federal Reserve chair Jerome, knocking the US dollar.
In a startling development, US prosecutors have launched a criminal investigation into Powell over a $2.5bn renovation of the Federal Reserve’s headquarters, and into his testimony about the project to the Senate banking committee in June last year.
The move is a dramatic escalation in the long-simmering tensions between the Fed and the Trump White House, with the US president repeatedly rubbishing Powell for not cutting interest rates more quickly.
After news of the investigation broke last night, Powell came out fighting, insisting that he had been threatened with criminal charges because the Fed had set interest rates “based on our best assessment of what will serve the public, rather than following the preferences of the president”.
#federal#reserve#chair#powell#investigation
📱American Оbserver - Stay up to date on all important events
🇺🇸
https://x.com/SavinoBalzano/status/1934542511730528379?t=47Ya1vjq0Kbps3qQqRYxrA&s=19
Quanto può costare una bugia?
Basterebbe chiederlo agli iracheni. Le menzogne dell’amministrazione #Bush, quelle del suo Segretario di Stato Colin #Powell, e quella #provetta passata alla storia. Conteneva un distillato di falsità.
Quel distillato ha avuto però la forza di aprire una voragine che ha inghiottito almeno mezzo milione di persone.
Da quella voragine sono emersi i mostri denunciati da Julian #Assange, che ha pagato a caro prezzo la sua testimonianza, perdendo a lungo la libertà.
Da quella voragine è emerso il carcere di #AbuGhraib.
E oggi ci stiamo riprovando.
Non esiste alcuna prova della volontà dell’#Iran di sviluppare armi nucleari. Nessuna.
Solo nuove provette, come quella mostrata il 5 febbraio 2003 davanti al Consiglio di Sicurezza delle Nazioni Unite.
Chi siamo noi? E, soprattutto, chi è #Israele per negare ad altri paesi ciò che #Netanyahu possiede senza ammetterlo?
Davvero qualcuno crede ancora alla narrazione dell’“unica democrazia del Medio Oriente”, del baluardo di civiltà in quella regione?
Nessuno vede ciò che Israele sta facendo a #Gaza? E un paese responsabile di simili azioni merita davvero di possedere un arsenale nucleare?
Stiamo liberando il popolo iraniano? Vogliamo “esportare la democrazia” come abbiamo fatto in Afghanistan? Con quale credibilità? Vogliamo liberare le donne di Teheran facendo piovere bombe sulle loro teste?
Sono già circa 400 i civili uccisi in Iran, e il numero salirà.
Il mondo non potrà tollerarci per sempre.
Key Crypto Events Coming March 7th
March 7th features key announcements: US unemployment rate for February, Powell's speech, and Trump's cryptocurrency summit at the White House. Coinbase CEO Brian Armstrong supports a US crypto reserve focused on Bitcoin. Notably, a transfer of 1,241 BTC (about $116.97 million) occurred between unknown wallets. Follow the updates! sourcetransaction details
#Crypto#BTC#US#Trump#Coinbase#Reserve#BrianArmstrong#Powell#Unemployment#WhaleAlert#Bitcoin#Blockchain#Investment#Finance#Summit#March7#MarketNews#CryptoRegulation#DigitalAssets#Tech