Наверняка вы замечали, что в 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
Microsoft Community Conference 2024 | Uzbekistan
Join us for a premier gathering of the Microsoft Developers Community in Uzbekistan! The annual Microsoft Community Conference is back and promises an unparalleled experience of innovation and technology. Mark your calendar for November 30, 2024, and get ready to immerse yourself in the latest advancements and ideas shaping the tech industry.
🎉 Highlights:
• Inspiring Keynote Presentations: Hear from leading tech innovators and industry experts.
• Interactive Workshops: Explore hands-on sessions with the latest Microsoft tools and technologies.
• Engaging Panel Discussions: Dive into trends and best practices shaping today’s tech landscape.
• Networking Opportunities: Connect with fellow developers, tech professionals, and enthusiasts.
📅 Date: November 30, 2024
📍 Location: Tashkent, Uzbekistan
Don’t miss out on this exciting opportunity to learn, network, and grow within a vibrant community. Whether you're a developer, tech professional, student, or simply passionate about technology, this is an event you won’t want to miss!
🔗 Register Now: https://mdcuzbekistan.com/register
Stay tuned for more updates and join us in shaping the future of technology in Uzbekistan!
#MDCConf2024#MicrosoftDevelopersCommunity#UzbekistanTech#TechConference#CommunityEvent
@mdcuzbekistan
Microsoft Community Conference 2024 | Uzbekistan
Join us for a premier gathering of the Microsoft Developers Community in Uzbekistan! The annual Microsoft Community Conference is back and promises an unparalleled experience of innovation and technology. Mark your calendar for November 30, 2024, and get ready to immerse yourself in the latest advancements and ideas shaping the tech industry.
🎉 Highlights:
• Inspiring Keynote Presentations: Hear from leading tech innovators and industry experts.
• Interactive Workshops: Explore hands-on sessions with the latest Microsoft tools and technologies.
• Engaging Panel Discussions: Dive into trends and best practices shaping today’s tech landscape.
• Networking Opportunities: Connect with fellow developers, tech professionals, and enthusiasts.
📅 Date: November 30, 2024
📍 Location: Tashkent, Uzbekistan
Don’t miss out on this exciting opportunity to learn, network, and grow within a vibrant community. Whether you're a developer, tech professional, student, or simply passionate about technology, this is an event you won’t want to miss!
🔗 Register Now: https://mdcuzbekistan.com/register
Stay tuned for more updates and join us in shaping the future of technology in Uzbekistan!
#MDCConf2024#MicrosoftDevelopersCommunity#UzbekistanTech#TechConference#CommunityEvent
@mdcuzbekistan
Exciting Announcement: The Tech Joined Us as a Media Partner!
We are proud to welcome The Tech as an official media partner of the MDC Uzbekistan. This partnership marks the beginning of an exciting collaboration to support all our initiatives, including hackathons, conferences, and other key events.
With The Tech’s support, we’re set to expand our reach and inspire even more developers across Central Asia. Together, we’ll continue building a stronger tech community!
#MicrosoftDevelopersCommunity#TheTech#MediaPartner#TechEvents#MicrosoftUzbekistan
@mdcuzbekistan