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

Резултати

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

Пребарај: #hkpolice

当前筛选 #hkpolice清除筛选
香港人的蘋果

@Appledailyhk26 · Post #55660 · 10.10.2023 г., 00:38

#英文#港聞 Oct 4: Yung Wai-yip was subdued for holding white flowers. People nearby question the necessity of the force used by the #HKPolice. Credit: boomheadhk 🍎保留一點真相、一些堅持: https://t.me/appledailyhk26 🍎蘋果報料熱線: @Appledailyhk_bot 🍎蘋民不蘋則鳴!2.0 https://t.me/hkerappledaily2

香港人的蘋果

@Appledailyhk26 · Post #56536 · 12.11.2023 г., 22:50

#英文#港聞 More info about #721YuenLongTerrorAttack from the book "Among the Braves". It says that there were 5 different triad groups involved in the attack. They had a WhatsApp group which the #HKPolice had access to. "A week prior, members of five separate triad groups joined a WhatsApp group to discuss plans to “defend their homeland,” Yuen Long. It was rare for these groups to come together, as they often clashed over their share of illicit business. As the triad groups coordinated their plans for July 21, a detective sergeant from the anti-triad bureau that oversaw the area was reading along. He had managed to gain access to the group chat, giving him unfettered insight into the plans." The article also reported that Stephen Ng, political assistance to the mainland affairs mentioned about "wear white only" dress code. "The political assistant to the secretary for mainland affairs had invited some others to join him at the banquet. He gave them a very specific dress code: Wear only white.”

Hong Kong Democracy Movement

@hkdmovement · Post #7841 · 23.09.2024 г., 03:13

5 years ago today, Chan Yin Lam passed away mysteriously. During 2019, many HongKongers went missing or died. Several times #HKPolice were caught throwing bags with the size of a human into the sea. Her body was found in the sea, naked, yet people knew her claimed that she was a diver. #HKProtest#neverforgiveneverforget #FreeHK

香港人的蘋果

@Appledailyhk26 · Post #56534 · 12.11.2023 г., 22:34

#英文#港聞 #721 After 4 years, more information about #721YuenLongTerrorAttack has been revealed as the trial against Lam Cheuk-ting, a former democratic lawmaker who claimed to be there to understand the situation. Witness B, who was a staff at the station time, said that police contacted the station through whatsapp to send 2 police to monitor the station on July 19th, 2 days before the attack. On 20th, police arranged to have 2 police to standby at the monitor room starting at 5:00PM on 21st. There were 2 police in the monitor room during the attack on 21st. Clearly, #HKPolice knew that the local thugs had planned the attack 2 days before the incident. 🍎保留一點真相、一些堅持: https://t.me/appledailyhk26 🍎蘋果報料熱線: @Appledailyhk_bot 🍎蘋民不蘋則鳴!2.0 https://t.me/hkerappledaily2

Hong Kong Democracy Movement

@hkdmovement · Post #7276 · 11.03.2024 г., 11:18

#HongKongers express fear as govt considers expanding #HKPolice power under proposed #Article23 security law. Extended detention period without charge and restrictions on legal representation raise concerns about #individualrights and freedoms. https://hongkongfp.com/2024/03/07/hong-kong-considers-extending-detention-period-of-arrestees-to-up-to-14-days-in-national-security-cases/ #HongKong#PolicePower

香港人的蘋果

@Appledailyhk26 · Post #56081 · 24.10.2023 г., 13:04

#英文#港聞 Oct 17: A student held piece of paper writing "721唔見人" at a college recruitment event which #HKPolice participated. It refers to the day no police showed up when thugs attacked citizens indiscriminately on July 21, 2019. The school security told him to leave soon after. #721YuenLongTerrorAttack #721YuenLongAttack #HKPoliceTerrorist 🍎保留一點真相、一些堅持: https://t.me/appledailyhk26 🍎蘋果報料熱線: @Appledailyhk_bot 🍎蘋民不蘋則鳴!2.0 https://t.me/hkerappledaily2

Hong Kong Democracy Movement

@hkdmovement · Post #7500 · 15.06.2024 г., 17:17

Jun 15: Leung Ling-kit wore a yellow raincoat with an umbrella standing at Pacific Place Patio at 4:30. He wrote “Carrie Lam kills Hong Kong” & “Black Cops are cold blooded” on a banner and hang it at the building for everyone to see. Police and negotiators went but did not allow anyone to go near him. At 9:15pm, he jumped down. That was the beginning of the 2 million+1 people march the next day. People still commemorate him in Hong Kong to this day while countless of #HKPolice was standing by as if having a flower in hand can damage #nationalsecurity. This is the excuse they use to arrest people anyway. The laws that we having been fighting against, the extradition bill, national security law & article 23 are laws that criminalize thoughts. #leunglingkit#HongKongProtest#5demandnot1less#fightforfreedom#standwithhongkong