Наверняка вы замечали, что в 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
LinkedIn’da topilgan maslahat:
Professional o’sishni tezlashtirish va atrofdagilardan farq qilish uchun biror soha yoki yo’nalishda “go-to-person”ga aylanish. “Go-to-person” - biror muammo yoki savol tug’ilganda murojaat qilinadigan odam: yo’nalish kattaroq kodning bir qismi, test qilish, biror freymvork, Kubernetes, Docker, biror usul va hokazo bo’lishi mumkin. Shu yo’nalishni topish va shu bo’yicha hamma suyanadigan, boradigan odamga aylanish odamning professional o’sishiga juda katta yordam beradi.
@farhodjon#growth
🌍 In November 2022, the world’s population reached 8 billion for the first time, doubling in just 48 years since 1974—a record pace in human history for global population growth. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, India gained over 13 million people—more than the total population of some countries. This rapid growth boosts its status as the planet’s most populous nation. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
🌍 In 2023, Ethiopia recorded the world’s highest annual natural population increase, adding nearly 2.7 million people in a single year—more than many countries’ entire populations. ✨
#population⚡#demographics⚡#growth⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
Leading Crypto VC Firms to Watch in 2023
Thanks for the feature! 💥
We're proud to be part of this ecosystem.
It's a privilege to be part of this Web3 future.
Let's keep building! ✨
#investment#community#growth
🌍 Over one million people are added to the world population roughly every five days. The fastest-growing regions are now in parts of Africa, where birth rates remain among the highest globally. ✨
#demographics⚡#growth⚡#continents⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography
👉more Channels
Good morning, good morning! ☀️ Looks like Darius had a good night's rest and is feeling even better than before.
———
Stage 2, Part 1 of the growth drive! Thank you all for your contributions to this - it's still in the works, albeit slowly!
Stage 2, Part 2 is in the works!
#art#growth#nsfw#hyper
Russia expects 3.9 percent GDP growth in 2024
📌 This is the result of a set of applied policies in the field of finance, infrastructure development, digitalization, building a knowledge economy, and improving the level of education of the population.
📌 "It was noted (at the APEC summit - ed.) that in comparison with other regions of the world in the economy (countries - ed.) APEC feel quite comfortable. GDP growth rates in APEC countries exceed the global averageaverage" - Russian Deputy Prime Minister Alexey Overchuk
#news#russia#nido_russia#economy#growth
https://t.me/nido_russia
🌍 The city of Lagos, Nigeria, is predicted to become the world’s most populous city by 2100. Rapid urban growth could bring its population over 80 million, surpassing today’s largest cities. ✨
#population⚡#growth⚡#megacities⚡#urbanization⚡#geography⚡#nature⚡#earth
👉subscribe Amazing Geography🌍
TON is an up-and-coming powerhouse that we're absolutely stoked about⚡
In this video, TON's Head of Incubation, Justin Hyun, shares some exciting insights about Ton Foundation and its role in the #ecosystem.
While TON is younger than other significant Layer 1 blockchains, its rapid #growth and evolution has led it to become one of the hottest projects in the #crypto market in the last month, and it appears that next year will be exciting for TON.
In terms of transaction speed and versatility, TON Foundation remains ahead of other Layer 1 blockchains. In addition to a quick block validation time, the blockchain provides several advanced scalability features, such as sharding support.
Needless to say, we are a fan of this amazing #work and we can't wait to see the innovations that TON is going to bring to this space in the coming years.