Что делать если нужно поставить какую-то 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
We are grateful to the participants for their strong commitment to enhancing tax transparency and combating cross-border tax evasion. IRAS remains dedicated to collaborating closely with industry partners to facilitate a smooth implementation process.
#LifeatIRAS#internationaltax#taxtransparency
Ever wondered how Singapore stays at the forefront of global tax cooperation? Our active participation in international discussions is one way we do so 💪 Just a few weeks ago, Deputy Director Pang Cheng Jong and Senior Manager Kenneth Lim from the International Tax and Relations Division represented the #IRASFam at the 48th OECD Working Party 10 meeting, contributing to crucial discussions that shape the future of international tax transparency and compliance.
Our team engaged with the OECD Business Advisory Group on the Amended Common Reporting Standard (CRS) and Crypto-Asset Reporting Framework (CARF), and worked with government delegates to develop interpretative guidance for both standards – work that will directly impact how these frameworks are implemented globally 🌍
Our active participation reflects Singapore’s longstanding commitment to international tax cooperation and reinforces our role as a trusted partner on the global stage 🤝
#LifeatIRAS#internationaltax#taxtransparency
💫 Proud to share that our #IRASFam represented Singapore at the 18th Automatic Exchange of Information (AEOI) Peer Review Group meeting, where Senior Assistant Director Ang Ming Kwan (International Tax and Relations Division – Exchange of Information Branch) participated as an International Peer Review Assessor alongside colleagues from the Global Forum Secretariat. Our team also engaged in productive discussions on maintaining consistency in peer review standards and made interventions to champion a level playing field for all jurisdictions.
🤝 Building meaningful connections with the Global Forum Secretariat members and fellow tax administrators has been invaluable. These partnerships drive our shared mission of advancing international tax transparency and compliance.
#lifeatIRAS#taxtransparency#internationalrelations
Earlier this month, together with MOF, our colleagues from the International Tax and Relations Division represented #IRASFam at the 20th Working Group on ASEAN Forum on Taxation. This meeting provided a platform for ASEAN Member States to learn about key international tax issues, including tax transparency, Base Erosion and Profit Shifting (BEPS) and UN developments.
During the forum, our team shared Singapore’s approach and progress in implementing the Crypto Asset Reporting Framework (CARF). Tax Director Gordon Cheong highlighted Singapore's enduring commitment to international tax transparency standards on Exchange of Information on Request, Common Reporting Standard and CARF.
We are grateful for this valuable opportunity to strengthen relationships and foster knowledge sharing with our ASEAN counterparts, reinforcing our commitment to regional collaboration in tax administration.
#LifeatIRAS#taxtransparency#ASEANcollaboration
Our team shared Singapore's journey in implementing the Amended Common Reporting Standard (CRS). Manager Nicole Kan highlighted both Singapore’s implementation progress in accordance with internationally agreed tax transparency standards and our philosophy that robust tax transparency standards are best achieved through genuine partnership with industry stakeholders. This collaborative approach has been instrumental in Singapore's successful CRS implementation.
The ASEAN forum reinforced that regional cooperation is essential - through shared experiences in digitalisation, transparency, and tax certainty, ASEAN administrations can build stronger, more efficient systems that benefit businesses and citizens alike 💪
#LifeatIRAS#taxtransparency#ASEANcollaboration#internationaltax
🎤 Assistant Commissioner Angela Ang contributed as a panellist, sharing our insights on the Common Reporting Standard. She wore two hats – one as an AEOI Peer Review Group member and another as an Assessed Jurisdiction.
🤝 Tax Director Gordon Cheong chimed in too, emphasising how we had teamed up with industry partners to implement CRS. He highlighted that we will continue to closely engage and partner with the industry as we implement the amended CRS and CARF in the coming years.
Read our announcement here and discover more about the Global Forum plenary meeting here.
#GlobalForum#AEOI#AutomaticExchangeOfInformation#CARF#TaxTransparency#GFplenary2024