Что делать если нужно поставить какую-то 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
US Sovereign Fund Eyes Bitcoin Investment
After Trump's new decree, bullish sentiments rise as Senator Lummis hints at potential government investment in $BTC that could drive significant market growth. Read more: Impact
#BTC#Crypto#VC#Trump#Senate#Investment#MarketTrends#Blockchain#DigitalAssets
Yellen confident Congress will raise debt ceiling
U.S. Treasury Secretary Janet Yellen said that it will be lawmakers' responsibility to raise the federal debt limit and expressed confidence that Congress would do so after the temporary reprieve runs out on Dec. 3
#Debt#Senate#JanetYellen#News#Reuters
Subscribe: http://smarturl.it/reuterssubscribe
Reuters brings you the latest business, finance and breaking news video from around the globe. Our reputation for accuracy and impartiality is unparalleled.
Get the latest news on: http://reuters.com/
Follow Reuters on Facebook: https://www.facebook.com/Reuters
Follow Reuters on Twitter: https://twitter.com/Reuters
Follow Reuters on Instagram: https://www.instagram.com/reuters/?hl=en
➖@reutersworldchannel➖
Promise of more focus on Nigerian Issuestowards speedy resolution
In my meeting yesterday and today with the Honorable Director, Diaspora & International Affairs, from National Assembly of Nigeria, Hon. Shadé Adepeju-Joseph, she promised to bring governmental attention to most of the plight that Nigerians face here, including unpaid student stipends/salaries and documentation. She also promised to take back home, much of the beautiful experience she got in Russia towards the betterment of bilateral ties, increased cultural exchange and trade.
Sputnik Africa also interviewed us to get to the bottom of these issues and brainstorm potential solutions. Stay tuned!
Yours in Service,
Dr. Godwin Ibe
Chairman, NIDO Russia
https://t.me/nido_russia/1770
#senate#Nigeria#nationalassembly#nido
🏛️🇺🇸SENATE BANS FEDERAL RESERVE CBDC — CRYPTO WINS BIG!
🔹 Senate votes 89-10 to BLOCK Fed from issuing digital dollar through 2030 💰
🔹 Bipartisan victory for financial privacy and traditional banking system 🏦
🔹 Prevents Fed from issuing CBDC directly OR through intermediaries 🚫
🔹 Freedom Caucus wants PERMANENT ban, not just temporary restriction 🔥
🔹 Trump position unclear — may demand voter ID bill passage first 🗳️
MASSIVE win for crypto advocates who warned CBDCs = surveillance! 👀
House vote uncertain, but momentum building against digital dollar 💪 Private crypto looking STRONGER! 🚀
#USNews#CBDC#crypto#Senate#privacy
@america
U.S. Senate to Form Crypto Subcommittee
The U.S. Senate Banking Committee, led by Senator Tim Scott, is set to establish its first cryptocurrency subcommittee, with Cynthia Lummis tentatively selected as chair. A vote to confirm her appointment and new members is expected soon.
Read more: link
#Crypto#Senate#USDC#XLM#Uniswap#Ethereum#AI#VC
Will Thom Tillis drop his block on Kevin Warsh’s confirmation by February 28?
⚖️ Senate procedure, leverage points, and timing signals now in focus.
📊 Track institutional developments:
🔗edgemarket.ai
#USPolitics#Senate#FederalReserve#KevinWarsh#Tillis
#USA#Ucraina#Israele#Taiwan
Il #Senate ha approvato, con 67 voti favorevoli e 27 contrari, la chiusura dell’accordo per la fornitura di aiuti per un ammontare pari a 95 miliardi di dollari a Ucraina, Israele e Taiwan.
Anche 18 senatori repubblicani hanno votato a favore dell’accordo, mentre Bernie #Sanders (#D|Centro-sinistra) è stato l’unico dem ad opporsi alla fornitura di aiuti a tali nazioni.
@OsservatorioEsteri
🚀 U.S. Treasury Secretary Urges Senate to Advance CLARITY Act
U.S. Treasury Secretary Besant has emphasized the need for the Senate Banking Republicans to review and advance the CLARITY Act for President Donald Trump's signature. According to Odaily, the legislation has been in development for nearly five years, aiming to secure the future growth of the financial industry.
#USTreasury#CLARITYAct#Senate#FinancialIndustry#USPolitics
#Elezioni#USA#Presidenziali
Urne aperte in #Vermont per le elezioni presidenziali, il primo Stato americano ad aprire i seggi ufficialmente per il voto nell’Election Day. Oltre ad eleggere il nuovo Presidente degli Stati Uniti si vota a livello federale per rinnovare completamente la #House ed eleggere 1/3 dei membri del #Senate. In alcuni Stati si vota per rinnovare le legislature statali, i governatori e le altre cariche esecutive oltre che votare diversi quesiti referendari.
In #Oregon si vota solo via posta, quindi non vi è un voto in presenza.
@OsservatorioEsteri
#USA#Senate
È morta all'età di 90 anni Dianne #Feinstein (#D|Centro-sinistra), Senatrice per la #California dal 1992 ed ex Sindaca di #SanFrancisco.
@OsservatorioEsteri
🚀 Wyoming's Digital Asset Regulation Discussed in Senate Roundtable
U.S. Senator Cynthia Lummis, chair of the Senate Digital Assets Banking Subcommittee, hosted a roundtable at the Wyoming State Capitol. According to Foresight News, the event included discussions with Comptroller Jonathan V. Gould and Governor Mark Gordon on the state's current digital asset regulatory landscape, the significance of a dual banking system, and how banking regulation can support responsible financial innovation.
Lummis emphasized Wyoming's leadership in the digital asset sector, noting that efforts initiated nearly a decade ago in the state have laid the groundwork for current federal initiatives. She highlighted Wyoming's comprehensive digital asset regulatory framework and expressed the importance of Comptroller Gould's visit to ensure federal policies reflect effective practices.
#Wyoming#DigitalAssets#Regulation#Senate#Banking#FinancialInnovation#Cryptocurrency#USPolitics
🚀 Treasury Secretary Advocates for Clarity Act Advancement Amid Senate Review
Treasury Secretary Scott Bessent has called on the Senate to expedite the passage of the Clarity Act, with Polymarket estimating a 59% probability of its approval by 2026. According to NS3.AI, the White House's Council of Economic Advisers released a report indicating that permitting stablecoin yields would minimally impact lenders' financial outcomes. The Senate Banking Committee is scheduled to evaluate the bill in the closing weeks of April.
#TreasurySecretary#ClarityAct#Senate#Stablecoins#Finance#Legislation#EconomicPolicy#BankingCommittee