Что делать если нужно поставить какую-то 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
Watch: Global business voices on China-US trade relations
China-US relations are in the spotlight as global business watches US President Donald Trump's visit to China and what it means for trade, investment and market confidence. In this episode of BizTalk, CGTN's Lincoln Humphries sits down with Fred Teng, president of the AmericaChina Public Affairs Institute, Chris Torrens, chairman of the British Chamber of Commerce in China, and Oliver Oehms, executive director and board member of the German Chamber of Commerce in China – North China; exploring investment sentiment, business trends and why China-US cooperation still matters in an uncertain global economy. #ChinaUS
via CGTN
Live: Beyond the buzz – What do young Americans really think about China-US relations?
What happens when young Americans experience China beyond the headlines? Join CGTN for a candid conversation with US creators and students living in China as they share firsthand perspectives on daily life, consumer trends, innovation and how these experiences are reshaping their understanding of China's economic dynamism and China-US connections. #ChinaUS
via CGTN
Coverage of US President Trump's departure after state visit to China
US President Donald Trump departs on Friday after a state visit to China. #TrumpChinaVisit#TrumpInChina#ChinaUS
via CGTN
US President Donald Trump to arrive in Beijing for state visit to China
US President Donald Trump arrives in Beijing on Wednesday for a three-day state visit to China. #ChinaUS#TrumpChinaVisit#TrumpInChina
via CGTN
📰 Presidential Aide Nikolay Patrushev gave an interview to Komsomolskaya Pravda newspaper(January 14, 2025)
Key points:
#USA
• The US establishment has been divided and lacks a common policy vision for the world and domestically.
• Trump’s core message is that he supposedly has a plan to revive pragmatic politics in the United States, which is expected to benefit both the state and its people. It has yet to be seen how this compares with the interests of other countries and nations.
• If Trump’s first term as president is any guide, the infamous deep state has a lot of clout in the USA. It can prevent Trump from pursuing his agenda.
• Trump will not view Ukraine as a priority. China is a much bigger concern for him.
• Trump has outlined his interests regarding Greenland, the Panama Canal, Mexico and Canada. There is an American tradition that consists of reshaping the world map to suit the US interests and interfering in the affairs of other countries across various continents.
• It seems unlikely that Trump sends the army to invade new states for the United States, as some have been saying. What is clear, however, is that the new administration will be proactive in asserting its interests in its dealings with all these countries.
#ChinaUS
• I believe that disagreements between Washington and Beijing will escalate, and it will be the United States that will intentionally fan these flames.
#RussiaChina
• For Russia, China has been and will remain a key partner as part of our privileged strategic cooperation. These relations are immune to momentary consideration and will endure regardless of who gets into the Oval Office.
#Ukraine
• Talks on Ukraine must take place between Russia and the United States without any other Western countries.
• The people of Ukraine remain a kindred, brotherly nation with our ties reaching back centuries, no matter what the Kiev propaganda mouthpieces say in their Ukrainisation frenzy. We do care about what is happening in Ukraine.
#Moldova
• Chisinau must be honest with itself and stop deceiving its people. The Moldovan authorities must recognise their mistakes and get down to mending fences instead of searching for enemies inside the country and in Transnistria.
#Europe
• We have nothing to discuss with either London or Brussels. For example, EU leadership has long lost the right to speak on behalf of many members including Hungary, Slovakia, Austria, Romania and several other countries which are interested in ensuring stability in Europe and have adopted a balanced position towards Russia.
Read in full
#Beijing_Review🇨🇳📕[PDF]⬇️
2 #October2025
#Weekly_Magazines
For learning, for free(dom).
@backupofmagazines
In this issue , the spotlight shines on #Xinjiang 70, celebrating seven decades of transformation in the autonomous region—from economic health to cultural heritage. Global topics include #PalestineRecognition, evolving #ChinaUS relations, and the healing potential of dialogue via the #XiangshanForum. Special features explore #RuralRevitalization and tech-driven change in Qingdao and Fujian, as #ScienceInnovation takes center stage. From the vibrant Grand Bazaar to a Somali expat’s vision, this issue captures both regional pride and global dialogue. #BeijingReview#CulturalDiversity#BeltAndRoad#EducationMatters#ChinaPerspective