Что делать если нужно поставить какую-то 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
Which linguistic term, named after an Oxford professor, describes the humorous mistake of swapping the initial sounds of two words, as in
➖“belly jeans” instead of “jelly beans”
➖“our queer old dean” instead of “our dear old queen”
A) Malapropism
B) Anagram
C) Palindrome
D) Spoonerism
@languagetrivia#term
😮Did you know that some words can mean their own opposite?
☯️ There's a cool linguistic phenomenon where certain words have two opposing meanings. These words are like linguistic chameleons, adapting to completely different interpretations in different scenarios!
Here are 5 examples of such words:
➖Sanction
➖To officially approve or permit something: The government sanctioned the new policy.
➖To punish or penalize: The country faced sanctions for its actions.
➖Dust
➖To remove dust: I dusted the shelves yesterday.
➖To add a layer of fine particles: She dusted the cake with powdered sugar.
➖Overlook
➖To supervise or watch over: The manager will overlook the project.
➖To fail to notice something: I accidentally overlooked that mistake.
➖Clip
➖To attach or fasten: He clipped the papers together with a binder clip.
➖To cut or remove: The gardener clipped the hedges neatly.
➖Screen
➖To show or display something: The theater screened a new movie.
➖To block or shield: Trees screened the house from view.
Can you think of any other words like that? Let me know in the comments 💬
Quiz Time!
What do we call words that mean their own opposite? 🧐
A. Antonyms
B. Palindromes
C. Contronyms
D. Capitonyms
Tap ❤️ if you found this interesting
@languagetrivia#theory#term
Sometimes, we don't want to be too direct with our words. For instance, instead of saying someone "died," we might say they "passed away." This way of softening our language helps us avoid discomfort or show sensitivity in delicate situations.
People use this kind of phrasing in various scenarios:
➖To avoid offending someone (e.g. saying "full-figured" instead of "overweight")
➖To speak politely about jobs (e.g. "sanitation worker" instead of "garbage collector")
➖To make bad news sound less harsh (e.g. "let go" instead of "fired" or ”downsizing” instead of “cutting jobs”)
➖To talk about sensitive topics (e.g. "use the restroom" instead of "go to the toilet" or ”gosh" instead of "God")
These phrases help us navigate social interactions tactfully, showing how language can soften or enhance our message.
What do we call this practice of using less direct language to soften or sugarcoat an idea?
Options:
A) Oxymoron
B) Metaphor
C) Hyperbole
D) Euphemism
Take the quiz below to see the correct answer
@languagetrivia#theory#term
❓What word hides behind the spoiler? Don't reveal it yet✋
"œ" and "æ" are examples of a ligature. A ligature occurs where two or more graphemes or letters are joined to form a single character. These were introduced in handwritten scripts and early printing to improve efficiency, aesthetics, and save space. In handwriting, they reduced the number of strokes needed to write certain letter combinations. In typesetting, they helped conserve space in narrow columns. For example, "œ" is used in French words like cœur (heart) and œuvre (work) and "æ" can sometimes be seen in English, as in encyclopædia.
So what is it called when two or more letters are combined into a single character like "œ" and "æ"?
A) Digraph
B) Ligature
C) Umlaut
D) Diphthong
Tap to reveal the correct answer:
These characters are called ligatures
Ligatures (Wikipedia)
List of English words that may be spelled with a ligature
And the other terms from above:
➖A digraph combines two letters for one sound (e.g., "sh")
➖An umlaut (¨) changes vowel sounds (e.g., regular "u" vs. "ü" as in über in German)
➖A diphthong blends two vowel sounds in one syllable (e.g., "ou" in house).
Tap ❤️ if you've learnt something new.
@languagetrivia#theory#term
What do you call it when a phrase or the components of a word get translated literally from one language to another and the original meaning is preserved?
For instance,
English "skyscraper" →
French "gratte-ciel" (“scrape-sky”),
German "Wolkenkratzer" (“cloud scraper”),
Spanish "rascacielos" (“scrape skies”).
Press ❤️
Follow @languagetrivia to learn more about languages
#theory#term
There is a phenomenon where some twins develop a private “language” understood only by them, often using invented words, sounds, or gestures. It usually emerges in early childhood due to their close bond and shared environment and may fade as they learn standard language skills.
What is the name of this phenomenon?
Join 🦫@languagetrivia for more interesting language facts
#theory#term
Did you know that the word apron has an interesting history? Originally, it was napron, derived from the Old French word naperon, meaning a small tablecloth or napkin. Over time, due to the way people spoke, the phrase “a napron” was misinterpreted as “an apron,” and the word changed!
This linguistic shift happens when the boundaries between words are reinterpreted, often influenced by how words are pronounced. Another example is nickname, which came from "an eke name" (meaning an additional name) but was turned into "a nickname."
What is this phenomenon, where words change due to a reinterpretation of their boundaries, called?
A. Rebracketing
B. Metathesis
C. Semantic Change
D. Semantic Broadening
@languagetrivia#etymology#theory#term
With the help of what literary technique is the humorous effect in this meme achieved?
Options:
A) Spoonerism
B) Pun
C) In-joke
D) Malapropism
Take the quiz below to find out
@languagetrivia#meme#term
The ampersand (&) symbol has a rich history intertwined with the evolution of the English alphabet. Originally, it was a ligature of the Latin word “et,” meaning “and.” Over time, this symbol became so integral to writing that it was included as the 27th character in the English alphabet, following ‘Z’. When reciting the alphabet, people would conclude with “X, Y, Z, and per se and,” which translates to “and, by itself, and.” This phrase was eventually slurred together into the single term “ampersand.”
Source
Tap ❤️ if you found this interesting
@languagetrivia#theory#term#symbol#etymology