Что делать если нужно поставить какую-то 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
#Oman🇴🇲
This oasis is called Vadi Bani Khalid and is one of the main attractions of the country. The Vadi landscape is striking in its diversity: here you will find both green oases with palm trees, and arid canyons with colorful cliffs. Picturers palm groves, transparent lakes and hills made of soft, golden sand. This place seems to invite us to plunge into an oasis of calm and harmony with nature.
🇮🇷🇴🇲According to an Associated Press report, Iran and Oman will collect tolls from all ships transiting the Strait of Hormuz during the two‑week ceasefire.
✍️ Recall Oman’s stance during the treacherous American attacks on the port of Salalah. Oman position and congratulate for the elect of new Iran's supreme leader so infuriated Trump that he even insulted the Sultan of Oman. Among the Arab nations, Yemen (Sana’a government) and Oman stood on the right side and did not bet on the losing horse! The current state of the UAE, Bahrain, Saudi Arabia, Kuwait, and Jordan is a testament to the wisdom of Omani policy.
#Iran#Oman
🇮🇷🤝🇴🇲 A new protocol has been finalized by Iran regarding the Strait of Hormuz and has been communicated to the IRGC Navy for implementation. This new protocol is based on the assumptions that, firstly, Iran’s enemies have no right to use the strait, and secondly, Iran must secure and compensate for all damages it has suffered through the strait.
👉Oman has agreed to cooperate with Iran’s new protocol in the Strait of Hormuz.
#Iran#Oman
🇮🇷🇴🇲Iran's Khatam al-Anbiya Central Headquarters: The Salalah port incident is suspicious
🔹The spokesperson for the Central Headquarters of Khatam al-Anbiya (PBUH), in response to the suspicious attack on Salalah port in Oman, said:
"The incident that occurred at Salalah port in the friendly, neighboring, and brotherly country of Oman appears very suspicious. The Islamic Republic of Iran is investigating this matter. The security and national sovereignty of Oman are respected by the Armed Forces of the Islamic Republic of Iran."
✍️ As we have said before, Iran has no intention of attacking civilian sites, and if it did, human casualties and financial damages in Arab countries would be unimaginable. The attack on Oman, which is considered a friend of Iran, is also very suspicious. Salalah port is also very far from southern Iran in terms of distance, and there is a possibility that this port was attacked by American drones. The U.S. is under pressure and spares no action against Iran!
#Iran#Oman
🇮🇷#Iran - 🇴🇲#Oman: Two alleged Iranian drones have struck Salalah Port in Oman, damaging port cranes. The Omani government has released a statement condemning the attack, stating that one port worker was “moderately injured.”
🇨🇳🇮🇷🇴🇲China urges Gulf states to unite against external interference amid widening conflict
China's foreign minister urged Gulf countries to unite to oppose external interference on March 2, after US-Israeli attacks on Iran triggered a widening conflict in the region.
China hoped that the Gulf states would strengthen unity and develop neighbourly friendship to "keep their future and destiny in their own hands", Chinese Foreign Minister Wang Yi said in a phone call with his Omani counterpart, according to a statement released by the ministry.
In a phone call with Iranian Foreign Minister Abbas Araqchi on the same day, Wang said he believed that Iran could maintain national and social stability as well as attach importance to the legitimate concerns of its neighbours, a separate statement showed.
#China#Iran#Oman
@asianomics
🇮🇷🎙Leader of Iran: The attacks in Oman and Turkey are not Iran's doing.
✉️ Seyyed Mojtaba Khamenei, the Leader of Iran, stated in this year's Nowruz message:
"I point out that the attacks which took place in Turkey and Oman—both of which have good relations with us—against certain locations in these countries were by no means carried out by the armed forces of the Islamic Republic or any other forces of the Resistance Front. "This is a deception employed by the Zionist enemy using the false flag tactic" to sow discord between the Islamic Republic and its neighbors, and it may also occur in some other countries."
#Iran#Oman#Turkey