Что делать если нужно поставить какую-то 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
Historic Settlement: EEOC Resolves AI-Driven Age Discrimination Case
The Equal Employment Opportunity Commission (EEOC) has reached a groundbreaking settlement with iTutorGroup for $365,000 over allegations of AI-driven age discrimination. This marks the first-ever settlement against AI-powered recruitment tools in the US.
The EEOC filed the lawsuit in May 2022, accusing iTutorGroup of using an algorithm that automatically rejected older job applicants based on their age. Women over 55 and men over 60 were disproportionately affected by this automated process, which violated the Age Discrimination Act's protections for individuals aged 40 and above.
With litigation initiated in the U.S. District Court for the Eastern District of New York, the EEOC's efforts to conciliate prior to legal action were unsuccessful. As a result, the case was set for a settlement conference in October 2023. However, the EEOC has now settled the case for $365,000, underlining the significance of this legal victory.
As part of the consent decree, iTutorGroup is barred from automatically rejecting candidates based on age or gender. The company is required to adhere to non-discrimination laws and collaborate with the EEOC to establish policies that prevent unlawful discrimination in the future.
This lawsuit is likely to set a precedent for future cases involving HR Tech tools. The ongoing regulatory focus on automated employment decisions calls for responsible and compliant AI use to avoid legal consequences and uphold fairness.
#AI#Law#LegalTech#EqualOpportunity#Discrimination#AIEthics
US: New Federal Privacy Bill Aims to Safeguard Against AI-Driven Discrimination
Greetings! Senator Maria Cantwell, head of the Senate Commerce Committee, has highlighted that her introduced federal privacy bill could serve as a protective shield against discrimination fueled by artificial intelligence. Speaking at the Washington state's Future of AI forum, she underscored both the potential of AI and the necessity for "guardrails" to prevent potential risks.
Cantwell expressed concerns about AI's potential discriminatory applications, which might lead to unfair employment or loan practices. She emphasized the importance of her privacy legislation, designed to safeguard individuals from such biases.
While not providing specific details during the forum, Cantwell's spokesperson indicated that she was referring to the Consumer Online Privacy Rights Act, initially introduced in 2019 and re-introduced in 2021. The bill proposes several key provisions, including requiring companies to obtain consumers' opt-in consent for behaviorally targeted ads and prohibiting discriminatory ad targeting based on factors such as race, religion, or sex.
The legislation also aims to hold companies accountable for using algorithms in housing, education, job, or credit ads. Cantwell's advocacy reflects a growing awareness of the need to regulate AI applications to ensure fairness and protect individuals' rights.
#AI#Privacy#Discrimination#Legislation#AIEthics#Law
Lithuania Bans Property Purchases by Russians and Belarusians
The Lithuanian Parliament committee has approved a ban on Russian and Belarusian citizens buying real estate in Lithuania. Exceptions apply only to those already residing in the country, but transactions near military sites remain prohibited. This broad ban targets nationality rather than specific sanctioned individuals. Previously, Lithuania tightened rules by revoking residence permits from Russians visiting their homeland.
#Lithuania#Russia#Belarus#RealEstate#Discrimination
The main news of Russia and the world ishere.
In 1968, teacher Jane Elliott divided her students by eye color (blue vs brown) to show how discrimination works. One group was labeled “better” and given privileges. The other was treated as “worse.” Children quickly changed behavior and school performance, proving how labels and power create prejudice.
🧠👀
(Read more 1)
(Read more 2)
@googlefactss
#Psychology#SocialExperiment#JaneElliott#Discrimination#Education#History
🔴 APPEL À SOLIDARITÉ JURIDIQUE
L’association Sos Donbass recherche un avocat engagé, prêt à défendre ses intérêts gracieusement face à des cas de discrimination préoccupants.
➡️ Refus d’ouverture de compte bancaire, alors même que la loi française garantit ce droit à toute personne morale ou physique.
➡️ Fermeture arbitraire de plateformes de dons telles que HelloAsso, AssoConnect, Stripe, nous empêchant de mener à bien nos actions humanitaires.
🎯 Si vous êtes avocat ou connaissez un professionnel prêt à s’engager pro bono pour La Défense de nos droits fondamentaux, contactez-nous.
📩 [email protected]
📨message privé
🙏 Merci de partager cet appel autour de vous. Ensemble, faisons valoir la justice.
#AppelAvocat#Discrimination#SOSDonbass#DroitsFondamentaux#Solidarité#ProBono