Что делать если нужно поставить какую-то 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
Kevin Warsh, a New Chair of the Federal Reserve
Trump has announced Kevin Warsh as his nomination for the next chair of the Federal Reserve, selecting a candidate who has been an outspoken critic of the US central bank.
The move ends months of speculation about who the president would pick to replace Jerome Powell, as he waged an extraordinary campaign to influence policymaking at the Fed by repeatedly calling for interest rate cuts. Powell’s second term as chair is due to end in May.
Writing on his Truth Social platform, Trump said: “I have known Kevin for a long period of time, and have no doubt that he will go down as one of the GREAT Fed Chairmen, maybe the best. On top of everything else, he is ‘central casting’, and he will never let you down.”
Warsh, 55, a former Federal Reserve governor who has deep ties to Wall Street, had previously interviewed for the job of chair in 2017 when the role went to Powell, whose term ends in May. Trump’s pick will have to be confirmed by the Senate.
Mark Carney, the Canadian prime minister and former governor of the Bank of England, said in a social media post that Warsh is “a fantastic choice to lead the world’s most important central bank at this crucial time”.
The dollar strengthened early on Friday after it was reported that Warsh was expected to be Trump’s choice, but then eased back after the nomination. Gold fell by 4.8% to $5,132 an ounce. Wall Street opened slightly lower.
Warsh has warned about inflation risks in the US in the past, but has also echoed Trump’s critique of the Fed for being too slow to cut interest rates.
High interest rates can alleviate inflation at the risk of upping unemployment. Rates are currently at a range of 3.5% to 3.75%, which most economists at the Fed currently see as neutral to prices and unemployment.
Since resigning from the central bank in 2011 over its post-financial crisis stimulus package, Warsh has criticised it publicly on multiple occasions.
In April last year, he issued a stinging attack, saying the institution’s central bankers should not be treated as “pampered princes” and it too regularly “opines on matters outside its remit” which has led to “systemic errors” in its main role of trying to keep prices stable.
Warsh has been a longtime critic of the ultra-loose monetary policy pursued by the Fed since the financial crisis, including the central bank’s expanded balance sheet.
He had previously been seen as a monetary policy hawk, but appears to have aligned himself with the White House’s push for lower borrowing costs.
#chair#federal#reserve#trump#carney
📱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
🇺🇸