Что делать если нужно поставить какую-то 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
#rule
Juniorlar - Sizni, yangi ishga kirgan kompaniyangizga, foydangizdan ko'ra zararingiz ko'p bo'lishi mumkin, shuning uchun, "meni eshshakdek ishlatib arzimagan summa beryapti", "ketaman bu ishxonadan" deb siqilavermang.
Sizni yozgan kodlaringizni baribir kimdir, soatini narxi qimmat bo'lgan tajribali birortasi vaqtini ketqazib, tekshirib chiqadi.
Mobodo tekshirmasdan nimadir xato narsa loyihaga o'tib ketsa, zararingiz 10x, 100x, 1000x bo'lishi mumkin. 1-2 ta tanish, o'rtoq juniorlar salgina yaxshiroq oylikli ishga kirdi degani, sizam shunaqasiga kirishingiz kerak, boshqasiga dam degani emas. Yana o'ziz bilasiz, Hojiboy aytadiyu: "Qorbobo" deb
Ha aytgancha, hoy middle, seniorlar, siz junior paytingiz, ishxonangizni qanchaga "kirgizib" yuborgansiz? ))
⌨️⌨️⌨️⌨️⌨️
The appointment of Mojtaba Khamenei was welcomed by Yemen’s Houthi rebels, who are backed by the Iranian regime.
“We congratulate the Islamic Republic of Iran, its leadership and people, on the selection of Sayyid Mojtaba Khamenei as Supreme Leader of the Islamic Revolution at this important and pivotal juncture,” the group said in a statement on Telegram.
Mojtaba Khamenei’s elevation marks the first time since the 1979 Islamic revolution that Iran’s supreme leadership has passed from father to son.
It is a development likely to ignite debate inside Iran about the emergence of a dynastic system in a state founded explicitly to overthrow hereditary rule after the shah.
Ayatollah Ali Khamenei, who ruled for 37 years, was killed in a US-Israeli strike on Tehran on 28 February, on the first day of the war with Iran.
Across Iran’s political and security establishment, officials moved swiftly to welcome the appointment of Mojtaba Khamenei as the country’s new supreme leader.
The Revolutionary Guards declared they stood ready to follow him, signalling broad backing from the country’s core institutions.
Earlier in the day, in a post on X in Farsi, the Israeli military said it would continue pursuing every successor of Ali Khamenei and would pursue every person who sought to appoint a successor for him.
For many analysts, Khamenei’s appointment is a symbolic move designed to make the regime still appear strong and determined not to bow to western pressure.
The 56-year-old cleric has never held elected office nor formally occupied a senior position within Iran’s government. He has spent much of his life at the centre of power in Iran while remaining largely out of public view.
To his supporters, Khamenei represents continuity with the ideological line established by Ayatollah Ruhollah Khomeini and maintained by his father. To critics, his rise raises uncomfortable questions about the concentration of power – and the possibility of hereditary leadership in a state founded in revolt against monarchy.
Oil prices surged more than 25% on Monday to their highest levels since mid-2022, as major Middle Eastern oil producers cut supply because they cannot safely send shipments through the strait of Hormuz to refiners worldwide.
Traffic through the strait was largely closed after Iran attacked at least five ships, with a limited number of tankers transiting, choking off a key artery accounting for about 20% of global oil and LNG supply.
#khamenei#mojtaba#son#iran#leader#rule
📱American Оbserver - Stay up to date on all important events
🇺🇸
Ali Khamenei’s Second Son Took His Place
Who is He?
⌨️⌨️⌨️⌨️⌨️
Mojtaba Khamenei, the second son of the late Iranian supreme leader Ayatollah Ali Khamenei, has been chosen as his successor, as the war enters its 10th day and fresh missile and drone strikes reverberate across the Middle East.
After members of the clerical body responsible for selecting Iran’s highest authority announced the decision on Sunday, Iranian institutions and politicians, from the foreign ministry to lawmakers, issued statements expressing their allegiance.
“We will obey the commander-in-chief until the last drop of our blood,” a statement from the defence council said.
The move could lead to a further escalation of the war, given Donald Trump had already acknowledged that Mojtaba Khamenei was the most likely successor and made clear he considered him an “unacceptable” choice.
The US president said earlier on Sunday that Iran’s next supreme leader was “not going to last long” if Tehran did not get his approval first.
When asked about the appointment during an interview with the Times of Israel published late on Sunday, Trump was reported as saying: “We’ll see what happens.”
In the same interview, Trump said a decision on when to end the war would be a “mutual” one, together with Netanyahu.
Trump also asserted that Iran would have destroyed Israel if he and Netanyahu had not been around. “Iran was going to destroy Israel and everything else around it (…) We’ve worked together. We’ve destroyed a country that wanted to destroy Israel,” he was quoted as saying.
The Israeli military said it had launched a wave of strikes on Monday targeting “regime infrastructure” in central Iran, the first such announcement since the appointment of the new supreme leader.
The military also announced strikes on the Iran-backed militant group Hezbollah in Lebanon.
Iran and its proxies appeared to have launched attacks, too, with rocket and drone strikes targeting a US diplomatic facility near Baghdad’s international airport that were intercepted by the C-RAM defence system, said police sources.
A drone strike targeted a US military base near Erbil airport in Iraqi Kurdistan, security sources said, while Saudi authorities reported intercepting a drone east of its northern al-Jawf region.
In Bahrain, the health ministry reported 32 people were wounded overnight by an Iranian drone attack on the island of Sitra.
They include a 17-year-old girl who suffered severe head and eye injuries, and a two-month-old baby, according to the ministry.
Iranian state media also showed a projectile said to have been launched at Israel bearing the slogan: “At your command, Sayyid Mojtaba,” using an Islamic honorific.
#khamenei#mojtaba#son#iran#leader#rule
📱American Оbserver - Stay up to date on all important events
🇺🇸