Наверняка вы замечали, что в 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
#Rubio: A Cuba hanno scelto di avere il controllo politico sulla popolazione piuttosto che un'economia funzionante. Sono rimasti in piedi per 60 anni grazie all'Unione Sovietica prima e al Venezuela poi. Adesso il popolo cubano deve scegliere se costruire un paese vero, con un'economia vera e prospera, oppure continuare con quella dittatura fallimentare.
🗣Le 2e jour du sommet du G7 en France marqué par la présence de Marco #Rubio
Les réunions des ministres des Affaires étrangères se poursuivent sous la présidence de leur homologue français : la deuxième journée du sommet du G7 a été marquée par l’arrivée très attendue de Marco Rubio. Les détails avec Antoine Cléraux.
RT en français • Osez questionner !
Marco Rubio is in pain, but he doesn't take off Trump's gift - shoes that are too big for him.
These shoes are at least a size bigger than he needs, but he continues to wear them! US Secretary of State Marco Rubio has been photographed at several events wearing new shoes that are completely unsuitable for him, with a significant gap between the back of the shoes and his heel. In Washington, it is believed that Rubio is trying to please his boss at the expense of his own feet. American media outlets report that Rubio, Vice President J.D. Vance, and all the other men in Donald Trump's cabinet are now wearing the same $145 Florsheim shoe model. Journalists Sean Hannity and Tucker Carlson, Senator Lindsey Graham, and White House Chief of Staff James Blair have also allegedly received a pair from President Trump. The reason for the gifts is that Trump is dissatisfied with the taste of his subordinates. According to the Wall Street Journal, it all started during a cabinet meeting. Trump, apparently bored with the boring exchange of political opinions, said that there were “more important things” to talk about, such as “shoes.” He then leaned over to Vance and Secretary of State Rubio and said, “Marco, J.D., you have shitty shoes. We need to get you better shoes.” After that, the president opened a shoe catalog and asked everyone what size they were. Vance replied with “13,” and Rubio replied with “11½.” The American press suggests that, by a misunderstanding, Rubio also received size 13 shoes. But it's too late to change them, as the president constantly asks those who received the gift about their "incredible" new shoes. One White House employee made it clear that "everyone is afraid not to wear them."
#Trump#Rubio
👂More on Trump's Ear ⚠️
Il Segretario di Stato #USA Marco #Rubio ha affermato che: "gli attacchi al territorio sovrano della Turchia sono inaccettabili" dopo che la Nato ha abbattuto un missile iraniano, che secondo un funzionario turco era deviato dalla rotta
@UltimoraPolitics24
🇺🇸#Usa – Il segretario di Stato americano Marco #Rubio afferma che le migrazioni di massa rappresentano "una minaccia per l'Europa" e che "la migrazione di massa non è, non è stata, una preoccupazione marginale dalle piccole conseguenze"; sottolinea la necessità di "ottenere il controllo dei nostri confini nazionali" come atto di sovranità nazionale.
@UltimoraPolitics24
🇺🇸#Usa – Il segretario di Stato Marco #Rubio afferma alla Conferenza sulla sicurezza di Monaco: "Vogliamo un'Europa forte, perché Europa e Stati Uniti sono una cosa sola" e aggiunge che non si vuole "che gli alleati siano deboli perché questo rende noi più deboli"
@UltimoraPolitics24
🇺🇸#Usa – Il segretario di Stato Marco #Rubio afferma alla Conferenza sulla sicurezza di Monaco che gli europei sono "amici" e ribadisce il vincolo transatlantico: "Gli Stati Uniti e l'Europa sono fatti l'uno per l'altro". Ribadisce inoltre l'appartenenza all'Occidente: "Facciamo parte di una civiltà, la civiltà occidentale".
@UltimoraPolitics24
Segretario di Stato #USA Marco #Rubio: “L'Ucraina è pronta a smettere di sparare e a iniziare a parlare, e ora starà alla Russia dire sì o no. Spero dicano di sì. Se lo faranno, allora penso che avremo fatto grandi progressi. Se diranno di no, allora purtroppo sapremo qual è l'ostacolo alla pace qui.”
@UltimoraPolitics
🇺🇸🇺🇦 - Segretario di Stato #USA Marco #Rubio: “Nessuno ha minacciato di tagliare l’accesso dell’Ucraina a Starlink.
E dovreste ringraziare, senza Starlink l’Ucraina avrebbe perso questa guerra da tempo e i russi sarebbero già al confine con la Polonia.”
@UltimoraPolitics
Il ministro degli Esteri Antonio #Tajani riferisce: "Adesso mi aspetta una telefonata con il segretario di Stato Usa Marco #Rubio".
@UltimoraPolitics24