Что делать если нужно поставить какую-то 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
🥊 Listing $DFC on Bitget — is it worth buying a token?
$DFC is the main token of the Definer ecosystem on the TON blockchain with more than 100 services on one platform. At the moment, the project has the largest community on the blockchain — more than 450k people, and the token itself is trading at a price of $3.14 on MEXC, is in the top projects on TVL and in the top 500 projects on CoinMarketCap.
Often, at the start of the listing, you can catch the best entry point and pick up the icons in the future.
🔍 Several reasons why you should look at buying $DFC:
1. The $DFC token is listed on MEXC and added to the telegram @wallet wallet. This means that new users coming to the $TON ecosystem see it. And this gives an even greater boost to the price and potential x's.
2. More than 25,000 active DFC wallets. The distribution of DFC on holders' wallets indicates the interest of whales.
3. The project and the token have direct support from $TON, Binance Labs and #DWF, the largest players in the ecosystem pumping market.
4. Capitalization is only $ 80 million, there is room to grow, cap #PEPE is $ 3 billion.
In addition, the Token2049 conference is approaching, where Durov will speak. This means that $TON and all the projects around it will get a big boost.🔥
Bidask Protocol — New DEX on TONand a Giveaway💵33,000
🅱️Bidask launched in mainnet just a few days ago — before that, the exchange was in the testnet for almost three months. The team claims that their swap model is faster, cheaper and more efficient than its analogues. Practice confirms: exchanges are instantaneous, and the 10-15 sec delay is just the time it takes for the wallet to pick up the transaction. Further optimization is already on the TonCore side.
💰The seed investor is DWF Labs (market maker and validator #TON). For a young project, this is a serious resource — #DWF is building its own ecosystem and strengthening the platforms it is a part of.
#Bidask — partner 🌑#TONFest. The festival will feature a raffle 💵 33,000, and you only need to complete three tasks:
✔️Make $10 swaps
✔️Provide $10 to liquidity pools
✔️Provide $20 to liquidity pools (first $10 does not count). Your $20 is locked in the pool until June 30, 2025.
We recommend the $TON/$USDT pairand be sure to follow the buttons inside TON Fest — otherwise the quest will not be counted.
Bidask DEX | Channel
🚀 DWF Labs Founder Predicts Older Coins Unlikely to Reach All-Time Highs
DWF Labs founder Andrei Grachev has expressed skepticism about the potential for older cryptocurrencies to achieve their previous all-time highs. According to NS3.AI, Grachev noted that while the market dynamics have evolved, many of these older projects have not adapted accordingly. This observation suggests a challenging future for legacy cryptocurrencies in the rapidly changing digital asset landscape.
#DWF Labs #Andrei Grachev #cryptocurrencies#all-time highs #NS3.AI #legacy cryptocurrencies #digital assets
The first HACK-A-TON by The Open Network (TON) in South Korea has just started! 🔥
Super excited to be one of their main sponsors 🚀🫡
Pop by to meet up with us, or any rep from BoomLabs, Ozys, and TAV (The Open Network, Alphanonce, VistaLabs).
Address: B1, 126, Teheran-ro, Gangnam-gu, Seoul, Republic of Korea
주소: 서울 강남구 테헤란로 126 B1 수호아이오
KR page: https://lnkd.in/g9e-eDtb
EN page: https://lnkd.in/gpsPXMWG
#dwf#TheOpenNetwork#TON#Telegram#Hackathon#Seoul#Boomlabs#Ozys#TAV#Alphanonce#Vistalabs
🚀 Market Conditions Present Opportunities for Strategic Investments, Says DWF Labs Co-Founder
The cryptocurrency market is currently experiencing a "very boring" phase, according to ChainCatcher. DWF Labs Co-Founder Andrei Grachev expressed on social media that while participants may engage in discussions or humor, significant activities such as financing, trading, investing, and business expansion are quietly underway.
Grachev noted that the current market environment poses challenges for major projects, exchanges, and companies to make new listings or significant announcements, as high-profile actions may not be effective at this time. He advised maintaining patience in investment portfolios and waiting for more opportune moments.
He emphasized that the market is not in decline but rather offers opportunities for seemingly mundane activities, such as buying and holding Bitcoin long-term or engaging in altcoin speculation. Grachev concluded that there is still much to do for builders and investors, while smaller investors should focus on learning, avoid lamenting losses, and enjoy the market they have chosen to enter.
#cryptocurrency#marketconditions#investmentopportunities#DWF Labs #AndreiGrachev#bitcoin#altcoin#longtermholding#speculation#investors#builders#patience#learning#BTC
DuckChain Secures $5M Funding
TON’s consumer layer for Web3 DuckChain has successfully raised $5 million in a funding round with participation from multiple investors including dao5, Offchain Labs, DWF Ventures, and others.
#DuckChain#Web3#Funding#TON#dao5#OffchainLabs#DWF#Investors#Ventures#Kenetic#Skyland#GeekCartel#GateLabs#PrestoLabs#Camelot#Quantstamp#Blockchain#Finance#Investment#Technology