TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #210 · 3 фев.

Что делать если нужно поставить какую-то 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

Резултати

Пронајдени 2 слични објави

Пребарај: #toodeep

当前筛选 #toodeep清除筛选

Comfort Zone and Challenging Yourself🤯 It is crucial for leading a successful and fulfilled life to constantly challenge yourself. It doesn't really matter how you define "success" - it applies to every imaginable domain in life. The moment you start getting too comfortable with where you are, what you do, etc., you know for sure you're stuck. What does it mean "challenge yourself" or "get out of your comfort zone”? To me, it means developing every possible part of your life by constantly seeking something new, something out of my standard perspective. Trying to understand other people's opinions even if your initial thought was "what a bullsh*t". Seeing the world through various perspectives and thereby expanding and improving your own. 🎯 That is what challenges me the most and gets me out of my comfort zone. I assume it's pretty much the same for lots of other people. I believe, "challenging oneself" is a certain framework, a certain mentality that one should be developing and improving night and day. It makes you aware that the world and people around you are much more complicated than you think. It should never stop. And it never does. That’s the true beauty of it. So, coming back to a more "down-to-earth" approach - your comfort zone is a setup of people you talk to on a daily basis, the way you do certain things, places you normally visit, things you typically buy, etc. I am not saying that you should change everything at once. No, that would be just impossible and stupid. We do need some things in life that are stable. However, when it comes to success or development of, let’s say, a particular skill, confronting "standard procedures" and “routines” is inevitable. Once a neural pathway is established, the brain doesn't give that much effort and attention to it since it would work pretty well automatically. This brain's ability is excellent for survival, but not for our case. 🧠 Since you want to be constantly improving at something, you gotta keep criticizing and questioning yourself, your skills, methods, knowledge, beliefs, etc. That is partially why young people tend to generate fresh and creative ideas as opposed to professionals that "know for sure" something isn't gonna work. Danger‼️: you don't want to have too much novelty and uncertainty. Because 1. It's pretty tough mentally to keep questioning what you think is a common truth, so you gotta be careful with that. 2. You want to get that positive feedback and some motivation to push you forward - we are not robots after all 🤖. My point is that you have to function on the edge of your capabilities, having a certain amount of established and proven routines/ truths AND on top of that, asking yourself enough questions so you neither get lost nor become too comfortable. Stay out of your comfort zone ✌️ @per_aspera_ad_astra_tg - share my channel with your friends! #TooDeep

Hashtags

🤳 Social Media Dopamine Loop — Introduction ❗️Disclaimer: I am not gonna dive deep into the biological origin and purposes of dopamine as a hormone. Writing this post I just wanna emphasize how dangerous it is to follow and crave dopamine without control. What’s the dopamine loop after all? This article sums it up pretty well. In a nutshell, it is a constant seeking of small and fast dopamine portions (or hits) that bring us short-term pleasure. It can be sugary food or drinks, it can be sex, binge-watching Netflix, playing video games, or even simple human interactions. 🤯Fun Fact: some scientists and writers were deliberately limiting their interactions with other people in the first part of the day in order to stay focused and not be distracted by peoples’ faces. Such an extreme approach comes from the fact that humans are extremely susceptible to faces. It takes a lot of our “RAM” to analyze and understand other human beings based on their facial expressions. So in order to perform at the highest, they made such sacrifices. Coming back to dopamine. The main problem with such dopamine hits is that they can be achieved pretty effortlessly, without working hard to attain them (and I am not saying that in order to enjoy something you should “deserve” it only by working hard). ☹️ Let’s have a step back for a while and imagine how it all looked like thousands of years ago. Obviously, we won’t compare the lifestyle of people living then and now. The basic brain functions and frameworks, however, haven’t changed much since then. 🧠 What we need as humans basically are 2 things: calories and bits of information. The first ones feed our body and brain in order to function, and the second ones are crucial for our brain and therefore for our survival. How? Our brain is an extremely energy-consuming organ since it constantly gathers data around us, analyses it, and makes decisions that, at that time, were crucial for our survival. 🏹 From that standpoint, in order to get enough calories, you had to hunt. Hunts can be extremely long and unsuccessful. Once you get it you should start thinking about getting more later. Total pain in the a**, to be honest. Same with bits of information — we are especially receptive to visual clues, movements, and changes in the landscape in order to detect potential predators, food, etc. We are simply wired that way which enabled us to survive till that day. All this brainwork performed by us is exhausting. The same behavioral and neural patterns apply today. What does it mean nowadays? Neither of these 2 resources is scarce now. Food — almost unlimited access. It’s nothing compared to thousands of years ago. Information — all around us. It’s actually overwhelming. No wonder obesity is taking over in developed countries and people are suffering more and more from depression, anxiety, and lack of energy. Like it or not, we (humanity) unconsciously broke the pattern that provided us with a healthy existence. 🍟 Funny enough, we actually can stop eating — that’s good news because otherwise we die or become less attractive mate partners. This mechanism works pretty well (on the other hand, given the amount of free porn and 0 effort to get sexual arousal I am not sure about that). However, when it comes to information therewas no need for evolution to develop a mechanism that would stop us from getting more information. I mean, why would you want that, right? More information means more chances of survival. Noone however expected that information will become available on THAT scale. Which has led, ironically, to disrupting our existence instead of improving it (apart from the overall civilizational progress, I mean). 📱So now, why can’t I stop scrolling on my app feeds? This question is connected to another one: why am I constantly in a bad mood, having depression or anxiety? I am gonna cover some tips in the next post since it’s gotten pretty big already. Let’s collect 20 “🔥”, so I will see if you liked the post. To be continued 🔜 #TooDeep #OffTopic