Что делать если нужно поставить какую-то 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
🔤🔤🔤🔤➖
These changes will come in ways that have repeatedly happened before. For example, from studying history, it’s easy to identify over-extended empires, develop indicators for how overextended they are, and see how overextended empires have suffered from being overextended.
In looking at what is happening now, it is natural to examine what is happening with the U.S., which now has 750–800 foreign military bases in 70–80 countries (site note: China only has 1) and has commitments that create expensive vulnerabilities all over the world.
To be sure, there is nothing precise about these indicators, the picture they paint, or the exact timing. For example, history has taught us that wars don’t always have definitive start dates with big military events followed by clear declarations of war.
The Assassination of Archduke Ferdinand, the German invasion of Poland, and the bombing of Pearl Harbor are actually the exceptions. Economic, financial, and military conflicts typically arise before there are clearly declared wars.
Historically, major wars were typically preceded by developments and indicators like military stockpiles and monies being drawn down; budgets, debts, money printing, and capital controls being built up; rival countries observing the countries fighting and learning what their strengths and weaknesses are; and the overextended leading world power facing the challenge of trying to fight wars on different fronts that are very far apart.
These factors all matter, and my measures of them indicate that we should be concerned.
The classic dynamic at this stage is for conflicts to intensify rather than subside, so what happens next will be influenced by how the U.S.-Iran war goes.
For example, there is already less confidence among some countries that the U.S. will defend them, which, when combined with the recognition that nuclear weapons are a great defensive as well as offensive power, is leading to more talk among countries’ senior policy makers about obtaining nuclear weapons and building up their stockpiles of them and other weapons, particularly missiles and missile defense systems.
#dalio#iran#trump#nuclear#weapons#military#bases
📱American Оbserver - Stay up to date on all important events
🇺🇸
🔤🔤🔤🔤➖
Most of these wars involve major nuclear powers, and there are also significant non-shooting wars (i.e., trade, economic, capital, technology, and geopolitical influence wars) that most countries are in. Together, these conflicts make up a very classic world war that is analogous to past “world wars.”
For example, past “world wars” consisted of interrelated wars that were generally slipped into without any clear start dates or declarations of war. Those examples of both past and current wars combine in a classic world war dynamic that affects them all.
Understanding how the sides are lining up and what their relationships are is very important.
It is quite easy to see objectively how the sides are lining up via indicators such as their treaties and formal alliances, their votes at the U.N., their leaders’ statements, and their actions. For example, one can see how China is aligned with Russia and Russia is aligned with Iran, North Korea, Cuba, and Venezuela, and how that group is largely opposed to the United States, Ukraine, most European countries, Israel, the GCC states, Japan, and Australia.
These alliances matter a lot in imagining how things will go for the relevant players, so they need to be considered when observing what’s going on and what’s likely to happen.
For example, we see that reflected in China’s and Russia’s votes at the U.N. on Iran needing to open the Strait of Hormuz.
Similarly, while it’s said that China is particularly harmed by the closing of the Strait of Hormuz, that is wrong because China’s mutually supportive relationship with Iran will probably allow oil going to China to get through. Plus, China’s relationship with Russia will ensure China gets oil from Russia.
China also has a lot of other energy (coal and solar), and it has a huge inventory of oil. Also noteworthy is that China consumes between 80% and 90% of Iran’s oil output, which adds to the power of its relationship with Iran.
All things considered, it appears that China and Russia are the relative economic and geopolitical winners from this war. Though to be sure, the United States is relatively advantaged in terms of global energy economics, because it is in the enviable position of being an energy exporter.
Studying history is immensely valuable to me and helps me contextualize current events.
For example, both an examination of several analogous cases in history and logic make it obvious that how the United States (the dominant power of the post-1945 world order) performs in the war with Iran (a middle power), how much money and military equipment it expends and depletes itself of, and how well it defends (or doesn’t defend) its allies will be watched by other nations and will enormously influence how the world order changes.
Most importantly, we know that what happens in the war with Iran will have huge implications for what other countries (most importantly, those in Asia and Europe) will do, which will have big implications for how the world order will change.
#dalio#iran#trump#nuclear#weapons#military#bases
📱American Оbserver - Stay up to date on all important events
🇺🇸
Ray Dalio:
The Great Investor On the War in Iran and the Contemporary World
🔤🔤🔤🔤➖
As a global macro investor for over 50 years who has needed to study all things that affected markets over the last 500 years to know how to deal what’s coming at me, it appears to me that most people tend to focus on and react to the attention-grabbing things that are going on at the time—like what is going on with Iran now—and miss the much bigger, more important, and longer-term-evolving things that are driving what is going on and what is likely to happen.
For instance, this week, headlines have focused on the recently announced two-week ceasefire of the U.S.-Israel-Iran war. But I believe the conflict in Iran is just one part of a larger potential world war, with countries like China, Russia, and Iran on one side and the United States and countries with U.S. military bases on the other.
I wish it were not true, but I fear we are entering a world war.
I wish it were not true, but I fear we are entering a world war.
Certainly, what will happen with the Strait of Hormuz (most significantly, whether control of passage through it will be taken away from Iran, and which countries are willing to spend how much blood and treasure to make that happen) will have many enormous repercussions all around the world.
There are also the issues of whether Iran will still have a capacity to inflict harm on its neighbors through missiles and nuclear weapons, of how many troops the U.S. will send to the region, of the cost of gasoline, and of the upcoming U.S. midterm elections.
All these near-term issues are important, but they lead people to miss the really big, even more important things. More specifically, because most people tend to have this short-term perspective, they now expect, and the markets are pricing in, that this war won’t last long, and when it ends, that we will get back to “normal.”
Virtually nobody is talking about the fact that we are in the early stages of a world war that isn’t going to end any time soon.
Interconnected conflicts
It may sound like hyperbole to say we are in a world war, but it is indisputable that we are now in an interconnected world that has a number of shooting wars going on (e.g., the Ukraine-Russia- Europe-U.S. war; the Israel-Gaza-Lebanon-Syria war; the Yemen-Sudan-Saudi Arabia-UAE war that also involves Kuwait, Egypt, Jordan, and other related countries; and the U.S-Israel-GCC-Iran war).
#dalio#iran#trump#nuclear#weapons#military#bases
📱American Оbserver - Stay up to date on all important events
🇺🇸