Наверняка вы замечали, что в Python есть удобная функция для получения переменной окружения
os.getenv(NAME)
И её "сестра" для создания или изменения переменных окружения
os.putenv(NAME, VALUE)
Но почему-то putenv() не работает как должно. Энвайромент не обновляется!
os.putenv('MYVAR', '1')
print(os.getenv('MYVAR'))
... и ничего 😴
Почему так?
На самом деле энвайромент обновляется, но это значение не добавляется в словарь os.environ.
Откройте исходник функции os.getenv(). Это просто шорткат для os.environ.get()
В то время как putenv() это built-in С-функция.
Словарь os.environ (или точней класс из MutableMapping) создаётся из энвайромента в момент инициализации. Функция putenv() самостоятельно его не изменяет.
В тоже время, когда вы создаёте или изменяете ключ в os.environ, автоматически вызывается putenv() в методе __setitem__().
То есть, технически putenv() всё делает верно, но в os.environ это не отражается. Можно проверить так:
>>> os.putenv('MYVAR', '123')
>>> os.system('python -c "import os;print(os.getenv(\'MYVAR\'))"')
123
Я объявил переменную в текущем процессе и вызвал дочерний процесс, который её унаследовал и получил в составе os.environ.
Аналогично при удалении переменной вызывается еще одна built-in функция unsetenv(), удаляющая переменную из системы.
Итого
▫️ Удобней всего явно обновлять переменные через os.environ
▫️ Есть способ неявно создать/удалить переменную через putenv/unsetenv, что не повлияет на os.environ но изменит энвайромент и передаст изменения сабпроцессам. Но так лучше не делать!
▫️os.environ это просто обертка для built-in функций putenv() и unsetenv().
#basic
🤖 MCP Protocol: когда AI наконец-то получил доступ к реальному миру
Вчера Anthropic выкатили Model Context Protocol для Claude Desktop. И это, похоже, реально меняет правила игры – AI наконец-то может работать с локальными сервисами напрямую.
На старте уже доступно 9 базовых инструментов, включая работу с файловой системой, базами данных SQLite, PostgreSQL, и Brave Search. Но самое интересное – протокол открытый, и можно писать собственные интеграции. Прямо сейчас, например, пишу через Cursor модуль для работы с Telegram – хочу дать Claude прямой доступ к чатам 🛠
Например, можно будет сказать "загляни в чат проекта X, принеси последние 50 сообщений" – и он просто сделает это. Никакого ручного копирования или потери контекста. Хотите понять, что происходило в чате за последнюю неделю? Claude проанализирует и составит отчет. Нужно написать большое структурированное сообщение с задачами для команды? Он сформулирует его на основе предыдущих обсуждений 🚀
И главное – всё работает локально, без отправки данных в облака. Claude получает доступ только к тому, что вы явно разрешили.
Сейчас активно тестирую возможности и пишу интеграцию с Telegram. Если получится реализовать всё задуманное – это серьезно изменит подход к ежедневной работе с сообщениями и командами 🤔
#AI#MCP#AIIntegration
P.S. Кстати, работа с файловой системой уже отлично работает. Claude сам находит и читает нужные документы в разрешенных папках. Очень удобно хранить просто в текстовых документах задачи и файлы контекста, хочу попробовать использовать как замену памяти в ChatGpt.
P.S.S Скоро запишу видео как это все подключить себе на маке🤵
Solana AI Agents Launched
EXMO.me has introduced a new crypto set called Solana AI Agents, which integrates artificial intelligence with Solana's blockchain. Despite ongoing market volatility, the representatives of EXMO.me see this as an opportunity to focus on the technologies of the future. Crypto sets allow users to invest in multiple assets simultaneously.
#Solana#AI#Crypto#Blockchain#EXMO#Investment#Volatility#CryptoPortfolio#Technology#Cryptocurrency#MarketGrowth#Innovation#Fintech#AIIntegration#DigitalAssets#Token
Onchain Builder + Streamer Prototype Coming Soon
Jesse Pollak, head of the Base protocol, predicts a high likelihood of an onchain builder + streamer prototype launching this year. The integration of AI will enable publishing at ten times the speed and facilitate live broadcasting. AI will assist with coding, design, and marketing as well. Read more on X.
#AI#Crypto#VC#Base#streaming#onchain#technology#innovation#AIintegration#publishing#livebroadcasting#coding#design#marketing#Prototyping#development#future
Transforming the Used Goods Market
Investors were initially skeptical of Shopify, yet it grew to 4.5 million stores. A similar transformation awaits the $350 billion used goods market, where 93% of stores are still offline. Innovations using AI can reduce digitalization challenges by 95%. This presents an opportunity for a new platform to revolutionize online reselling. For more insights, check this article: Cointelegraph
#Tech#AI#Ecommerce#UsedGoods#Innovation#AIIntegration#MarketGrowth#Digitalization#Reselling#Investment#Shopify#Startup#Entrepreneurship#Revolution#OnlineSelling#Future#Trends#Retail#Fintech#VC
🚀 WeChat Pay Launches AI Integration Toolbox for Seamless Payment Solutions
WeChat Pay has officially introduced an AI-native integration toolbox designed to offer merchants and developers a streamlined payment integration solution. According to ChainCatcher, this toolbox facilitates the rapid generation of payment function code through natural language commands.
The toolbox comprises Skill packages, AI-friendly documentation, and APIs, enabling one-click calls in mainstream AI development environments. Its 'verbal code generation' feature significantly reduces the development process from days to minutes, allowing quick integration of over 20 functions, including mini-program payments, H5 payments, refunds, and profit-sharing.
Additionally, the toolbox includes AI diagnostic capabilities that automatically identify code logic issues and provide suggestions for fixes, minimizing financial and system risks during integration. It also supports interface troubleshooting and legacy code upgrades for existing system developers. This upgrade further advances the standardization and AI adaptation of payment capabilities, lowering the digital business barriers for small and medium-sized enterprises.
#WeChatPay#AIintegration#PaymentSolutions#Developers#Merchants#AItoolbox#CodeGeneration#DigitalBusiness#SMEs#TechInnovation#PaymentAPI#Automation#SystemUpgrade
🚀 AI Event to Showcase Diverse Applications in Pop Culture
An event titled 'Super Creator Live - Creating Pop Culture with Prompts' is set to take place this Saturday. According to BlockBeats, the event is co-hosted by Beating and West Sea Voice and will feature ten demo works selected from numerous submissions. Participants include developers with deep technical expertise, influential content creators, and professionals from finance, music, and podcast industries.
The diverse backgrounds of the creators promise to offer intriguing perspectives on AI's integration into unexpected fields such as gaming, interactive design, sociology, emotional support, and metaphysics. Following the demo presentations, several prominent guests will engage in a roundtable discussion, focusing on the essence of creation and exploring how to define expression in the era of AI.
With only two days left until the event, interested individuals are encouraged to register promptly. The event will take place on April 11 at 13:30 UTC+8, with the location details available upon registration.
#AI#PopCulture#Event#Creators#Gaming#InteractiveDesign#Sociology#EmotionalSupport#Metaphysics#AIIntegration#Roundtable#Finance#Music#Podcast#Beating#WestSeaVoice#Demo#AIInCreation#Tech#ContentCreators