Что делать если нужно поставить какую-то 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
#Arizona: L'Amministrazione Trump ha emesso un mandato di sequestro per i registri elettorali dell'Arizona risalenti alle elezioni del 2020 nella Contea di Maricopa, la più popolosa dello Stato.
I dati richiesti riguardano sia le informazioni elettorali della Contea sia i risultati dell'audit effettuato dal Senato dello Stato. A questo proposito, il Presidente del Senato dell'Arizona Warren Petersen (R) ha dichiarato di aver "ricevuto e ottemperato a un mandato proveniente da un grand jury relativo al controllo effettuato dal Senato dello Stato dell'Arizona" e che i documenti sono ora nelle mani dell'FBI. Il mandato, invece, non è ancora arrivato agli uffici della Contea.
Si tratta della seconda Contea a cui vengono richiesti i dati elettorali risalenti alle elezioni presidenziali del 2020. La prima, quella di Fulton, aveva visto anche l'intervento della Direttrice dell'Intelligence Nazionale Tulsi Gabbard, presente al momento della perquisizione. Le due Contee, inoltre, condividono la caratteristica di essere al centro delle teorie del complotto circa presunte frodi elettorali a favore di Joe Biden. Riguardo a tali accuse, così come su molte altre riguardanti la vittoria di Biden nel 2020, non sono mai state rinvenute prove di frodi sostanziali capaci di ribaltare gli esiti elettorali.
Si tratta anche di un'escalation da parte dell’Amministrazione, che riapre le indagini sul 2020 nel tentativo di influenzare la gestione di tutte le elezioni successive.
#Arizona: Vi sarebbe un’altra persona ferita dalla Border Patrol, questa volta in Arizona. L’individuo sarebbe in gravi condizioni.
Al momento non siamo a conoscenza di ulteriori dettagli.
#newtgingrich : RT @EpochTimes: “It’s amazing to me what a big mess this is,” Gingrich said.
#Arizona gubernatorial candidate @KariLake deserves to see an “honest count” after nearly a dozen GOP attorneys described widespread election day problems in #MaricopaCounty, said @NewtGingrich. https://t.co/RZ5sItfMUS
🚀 DOJ and CFTC Seek to Block Arizona's Action Against Kalshi
The U.S. Department of Justice (DOJ) and the Commodity Futures Trading Commission (CFTC) have filed a motion in federal court to halt Arizona's criminal and civil enforcement actions against Kalshi. According to NS3.AI, the agencies contend that event contracts regulated by the CFTC are beyond the jurisdiction of state authorities and are governed by federal commodity law.
#DOJ#CFTC#Kalshi#Arizona#eventcontracts#commoditylaw#federalcourt#statejurisdiction
New Auction Insights Boost Marketplaces
Key to marketplace success: increase buyer-seller transactions. Traditional property listings stagnate; auctions may revitalize them. One startup captured 20% market share in 3 months with a unique auction mechanic. This strategy could apply across various sectors. Read more: fastfounder.ru
KuCoin founders admit to accusations of unlicensed money transfer, resulting in a $297 million penalty. Founders banned from leadership roles.
Arizona Senate passes Strategic Bitcoin Reserve Act, allowing investment of up to 10% of public funds in cryptocurrencies like Bitcoin. Bill moves to Senate Rules Committee for further approval. cryptobriefing.com
Ethereum spot ETF faces outflows of $136 million on Jan 27; current net asset value: $11.30 billion. sosovalue.com
Ledger co-founder kidnapped for €10 million ransom, rescued by police after disturbing threats. Part of the ransom has been tracked. straitstimes.com
#Marketplace#Auction#RealEstate#Bitcoin#Crypto#KuCoin#Ethereum#ETF#Ransom#Ledger#France#Investment#Arizona#Blockchain#Finance#Assets#Trading#Innovation#Tech#VC
🚀 Federal Judge Halts Arizona's Arraignment of Kalshi Over Prediction Market Contracts
A federal judge has issued a temporary restraining order preventing Arizona from proceeding with the arraignment of Kalshi on 20 criminal charges related to its prediction market contracts. According to NS3.AI, District Judge Michael Liburdi ruled that Arizona cannot conduct Kalshi's arraignment scheduled for Monday, April 13. The order prohibits Arizona from applying its gambling laws to contracts listed on designated contract markets regulated by the Commodity Futures Trading Commission (CFTC). The CFTC, which has filed a lawsuit against Arizona and two other states, contends that these event contracts are considered swaps under federal oversight.
#FederalJudge#Arizona#Kalshi#PredictionMarket#Contracts#TemporaryRestrainingOrder#GamblingLaws#CommodityFuturesTradingCommission#CFTC#Lawsuit#Swaps
U.S. States Embrace Bitcoin Reserves
A surge in U.S. states pursuing legislation for strategic bitcoin reserves highlights increasing institutional interest in cryptocurrency. 15 states, including Alabama, Arizona, Florida, and Texas, are taking steps to incorporate bitcoin into financial strategies, aimed at attracting businesses and enhancing economic stability. The federal conversation on a national reserve is beginning, as states like Arizona and Utah are closest to legislative success. This movement reflects a broader trend recognizing bitcoin's potential as a financial tool.
#Bitcoin#Crypto#Finance#Legislation#Investment#Blockchain#Arizona#Texas#Alabama#EconomicStability#PublicFunds#DigitalAssets#Utah#Kentucky#InstitutionalInterest#VC#SBR#MarketTrends#FinancialInnovation
🚀 Federal Agencies Challenge Arizona's Gambling Laws Against Kalshi
The Commodity Futures Trading Commission (CFTC) and the Department of Justice have requested a federal court to prevent Arizona from applying its gambling laws to Kalshi. According to NS3.AI, the agencies argue that contracts related to sports and elections are federally regulated swaps. Arizona has initiated criminal charges against Kalshi, with an arraignment set for April 13. Should the courts agree with the federal perspective, prediction markets could potentially function across the United States under a unified federal framework, rather than being subject to individual state gambling regulations.
#FederalAgencies#Arizona#GamblingLaws#Kalshi#CFTC#DepartmentOfJustice#FederalCourt#SportsContracts#ElectionContracts#PredictionMarkets#FederalRegulation#StateGamblingRegulations