Что делать если нужно поставить какую-то 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
#中環 站 出口 J3 - 香港會所大廈 由於需進行保養工程,預計於 12 月 5 日(星期四)方會重開
乘客請使用 出口 J1 - 終審法院
中環站出口位置 👉metroride.hk/42FfSLy
-
#Central Exit J3 - Hong Kong Club Building is closed and estimated to be re-opened on 5/Dec (Thu) for maintenance
Please use Exit J1 - The Court of Final Appeal
Exit locations of Central Station 👉metroride.hk/42FfSLy
#中環 站 出口 J1 - 終審法院 由於需進行保養工程,預計於 11 月 26 日(星期二)方會重開
乘客請使用 出口 J3 - 香港會所大廈
中環站出口位置 👉metroride.hk/42FfSLy
-
#Central Exit J1 - The Court of Final Appeal is closed and estimated to be re-opened on 26/Nov (Tue) for maintenance
Please use Exit J3 - The Hong Kong Club Building
Exit locations of Central Station 👉metroride.hk/42FfSLy
荃灣綫會喺 10 月 31 日(星期四)在深夜
加開由 #中環 站開出的空載列車 🌌🚇🎃
該站部分出口或會於道路封閉期間,實施人潮管理措施,請留意廣播及資訊螢幕,以及車站職員和警務人員的指示
#MTR#Halloween
Empty Tsuen Wan Line services from #Central will be operated late at night on 31/Oct (Thu) 🌌🚇🎃
Crowd management measures may apply for some exits at this station during road closure periods
Listen to announcements, see info screens and follow instructions from station staff or the police
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
🇺🇸
DEPO-COMPASS No 15Download (PDF 4.9 Mb)
This new issue of “DEPO COMPASS” reports key depository indicators summarizing the results of October 2022.
#depocompass#report#statistics#central#depository
deponet.uz|Tg|Fb|Inst|Youtube
DEPO-COMPASS No 14Download (PDF 5.9 Mb)
This new issue of “DEPO COMPASS” reports key depository indicators summarizing the results of September 2022.
#depocompass#report#statistics#central#depository
deponet.uz|Tg|Fb|Inst|Youtube
DEPO-COMPASS No 13Download (PDF 6.8 Mb)
This new issue of “DEPO COMPASS” reports key depository indicators summarizing the results of August 2022.
#depocompass#report#statistics#central#depository
deponet.uz|Tg|Fb|Inst|Youtube
New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of September 2022.
Download depo-REPORTER No 13 (PDF, 0.8 Mb)
#depo#reporter#news#central#depository#securities#issues
deponet.uz|Tg|Fb|Inst|Youtube
New issue of Uzbekistan Central Securities Depository’s monthly newsletter “depo-REPORTER” covering key depository news of August 2022.
Download depo-REPORTER No 12 (PDF, 0.8 Mb)
#depo#reporter#news#central#depository#securities#issues
www.deponet.uz|Tg|Fb|Inst|Youtube