Что делать если нужно поставить какую-то 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
G20 leaders pledge support for Afghanistan
The Group of 20 major economies is determined to tackle the humanitarian crisis in Afghanistan, even if it means having to coordinate efforts with the Taliban, Italian Prime Minister Mario Draghi said after hosting an emergency summit.
#News#Reuters#Taliban#Afghanistan
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
WARNING: GRAPHIC CONTENT - Taliban will step up mosque security after attacks
Large crowds of people gathered in the Afghan city of Kandahar to bury victims of an Islamic State suicide attack on worshippers as Taliban pledged to step up security at Shi'ite mosques
#News#Reuters#Taliban#Mosque
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Afghans seeking travel papers crowd passport office
Crowds of Afghans flocked to the passport office in Kabul desperate to get travel documents
#News#Reuters#Taliban#Afghanistan#Passports
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Future at stake for Kabul orphanage
The program director at a large Kabul orphanage says he is cutting back on the amount of fruit and meat he gives the children each week because the home is running out of money
#News#Reuters#Kabul#Taliban#Orphanage#Afghanistan
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
The oldest known use of oil paint was found in caves behind the Buddhas of Bamiyan in Afghanistan, dating to the mid-7th century AD. Artists used walnut and poppy seed oils to bind mineral pigments. The giant Buddhas were destroyed by the Taliban in 2001. The murals show Buddha scenes and reflect influences from China, India, and Eurasia, linked to Silk Road artists.
[Read more]
@googlefactss🎨🕌
#Afghanistan#OilPaint#Bamiyan#Taliban#SilkRoad#ArtHistory
The situation at our Blue Mosque in #MazarESharif is deeply disturbing and demands immediate action - @nytimes.
This is not merely a building — it is a vital part of our shared religious and civilisational heritage.
We call on the #Taliban regime to fulfil its primary responsibility: to commission Afghan and international experts and allocate public funds for urgent repairs.
Afghan political and business leaders must also contribute. My colleagues and I will certainly do our part. 🤝
We urge #UNESCO to give this restoration and conservation the highest priority.
Finally, we appeal to our neighbours — especially #Uzbekistan🇺🇿, #Iran🇮🇷, and #Türkiye🇹🇷 — to support this effort with their technical expertise and resources.
@president_uz@HakanFidan@araghchi
@unescowhc
#MazarESharif#CulturalHeritage#SaveBlueMosque
The Qur'an tells Muslims to be kind to each other, but to treat the infidels harshly. While Muslims do exactly the opposite of what God said.
#Turkey attacks the Muslims of Iraq, Syria and Libya, but has political, economic and military relations with USA and Israel.
#Saudi_Arabia, #Qatar, the United Arab #Emirates (Wahhabi) attack Palestine, Syria, Yemen and Lebanon, but they have deep friendly relations with the USA and Israel.
#Taliban (Wahhabi) terrorists are attacking Pakistan. Terrorists from #Azerbaijan and #Pakistan are attacking Iran. Iraq invades Kuwait.
#Egypt and #Jordan surrounded Palestine, but they have good relations with Israel and USA.
All regional governments must be destroyed, traitors like Erdogan must be overthrown.
https://t.me/YediotNewsChat
The name of this religious school is "Darul Uloom #Deoband".
This huge place is located in India. #Zionists pump deviant Islamic thoughts day and night and produce thousands of terrorists. After graduation, they join terrorist groups like #Taliban, #Al-Qaeda, #ISIS. #Mufti, #Maulvi and #Mamusta are taught that if you kill 5 Muslims, you will go to heaven.
What is the result of these schools? Have they been able to improve the critical situation of #Afghanistan and #Pakistan? Graduates of these schools spread war, poverty and ignorance among Muslims.
Did #Hindus who worship cows and burn Muslims alive set up these schools for the growth of Islam? Did the Hindus unite with Islam or did they establish it to fight between Islamic groups? Why don't these groups (Deobandi, #Salafi, #Wahhabi) fight with USA and Israel?
https://t.me/YediotNewsChat
October 11, 2021: Alaska quake, U.S. and Taliban, AstraZeneca, Prince Andrew, California oil spill
October 11, 2021: Alaska quake, U.S. and Taliban, AstraZeneca, Prince Andrew, California oil spill
1. An earthquake of magnitude 6.8 struck the Alaska Peninsula region, the European Mediterranean Seismological Centre said.
2. The United States said on Sunday the first face-to-face meeting between senior U.S. and Taliban officials since the hardline group retook power in Afghanistan was "candid and professional" and that the U.S. side reiterated that the Taliban would be judged on their actions, not just their words.
3. AstraZeneca's experimental COVID-19 drug has helped cut the risk of severe disease or death in a late-stage study, the British drug maker said, a boost to its efforts to develop coronavirus medicines beyond vaccines.
4. British police said they would be taking no further action after conducting a review of evidence relating to sex crime allegations against Queen Elizabeth's son, Prince Andrew, and the late U.S. financier Jeffrey Epstein.
5. Beaches in a southern California city that were shut because of an oil spill last week are set to reopen, authorities said in a statement.
#Alaska
#Earthquake
#UnitedStates
#Taliban
#Afghanistan
#AstraZeneca
#Covid19
#UnitedKingdom
#BritishPolice
#PrinceAndrew
#Epstein
#QueenElizabeth
#Headlines
#MorningNews
#Business
#News
#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
October 11, 2021: Alaska quake, U.S. and Taliban, AstraZeneca, Prince Andrew, California oil spill
October 11, 2021: Alaska quake, U.S. and Taliban, AstraZeneca, Prince Andrew, California oil spill
1. An earthquake of magnitude 6.8 struck the Alaska Peninsula region, the European Mediterranean Seismological Centre said.
2. The United States said on Sunday the first face-to-face meeting between senior U.S. and Taliban officials since the hardline group retook power in Afghanistan was "candid and professional" and that the U.S. side reiterated that the Taliban would be judged on their actions, not just their words.
3. AstraZeneca's experimental COVID-19 drug has helped cut the risk of severe disease or death in a late-stage study, the British drug maker said, a boost to its efforts to develop coronavirus medicines beyond vaccines.
4. British police said they would be taking no further action after conducting a review of evidence relating to sex crime allegations against Queen Elizabeth's son, Prince Andrew, and the late U.S. financier Jeffrey Epstein.
5. Beaches in a southern California city that were shut because of an oil spill last week are set to reopen, authorities said in a statement.
#Alaska
#Earthquake
#UnitedStates
#Taliban
#Afghanistan
#AstraZeneca
#Covid19
#UnitedKingdom
#BritishPolice
#PrinceAndrew
#Epstein
#QueenElizabeth
#Headlines
#MorningNews
#Business
#News
#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖