Environment variables are accessed through os.environ import os print(os.environ['HOME']). Or you can see a list of all the environment variables using:
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
CollectivesonStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
HowdoIaccessenvironmentvariablesinPython?
AskQuestion
Asked
11years,2monthsago
Modified
29daysago
Viewed
2.4mtimes
2749
362
HowdoIgetthevalueofanenvironmentvariableinPython?
pythonenvironment-variables
Share
Improvethisquestion
Follow
editedApr1at12:14
MateenUlhaq
21.2k1616goldbadges7979silverbadges123123bronzebadges
askedFeb5,2011at13:03
AmitYadavAmitYadav
28.5k66goldbadges4040silverbadges5252bronzebadges
0
Addacomment
|
15Answers
15
Sortedby:
Resettodefault
Highestscore(default)
Datemodified(newestfirst)
Datecreated(oldestfirst)
Helpusimproveouranswers.Aretheanswersbelowsortedinawaythatputsthebestansweratornearthetop?
Takeashortsurvey
I’mnotinterested
4003
Environmentvariablesareaccessedthroughos.environ
importos
print(os.environ['HOME'])
Oryoucanseealistofalltheenvironmentvariablesusing:
os.environ
Assometimesyoumightneedtoseeacompletelist!
#usinggetwillreturn`None`ifakeyisnotpresentratherthanraisea`KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
#os.getenvisequivalent,andcanalsogiveadefaultvalueinsteadof`None`
print(os.getenv('KEY_THAT_MIGHT_EXIST',default_value))
ThePythondefaultinstallationlocationonWindowsisC:\Python.Ifyouwanttofindoutwhilerunningpythonyoucando:
importsys
print(sys.prefix)
Share
Improvethisanswer
Follow
editedJul25,2021at20:57
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredFeb5,2011at13:18
RodRod
47.9k33goldbadges3434silverbadges5252bronzebadges
11
1
hellorod,thanksforyoureffectivereplyconcerning'default-installation';effectiveinpointofviewtounderstanditquicklyratherthangothroughthelinks.That’sreallyIappreciated:)butaboutmy(1)questionpleaselookatthecommandandoutputssnippetbelow:>>>importos>>>printos.environ['PYTHONPATH']Traceback(mostrecentcalllast):File"",line1,inFile"C:\Python25\lib\os.py",line435,ingetitemreturnself.data[key.upper()]KeyError:'PYTHONPATH'>>>printos.environ.get('PYTHONPATH')None>>>//PLZtobecontinue...//
– AmitYadav
Feb5,2011at14:47
Ina1stwayscriptisthrowingExceptionwhereaswith2ndonegivingNone.So,isthereanywaytogetitmeaningfulvalueoramIdoinginawrongway???Amit.
– AmitYadav
Feb5,2011at14:49
9
os.environisadictionary.TryingtoaccessakeynotpresentinthedictionarywillthrowaKeyError.ThegetmethodsimplyreturnsNonewhenthekeydoesnotexists.DoyouhavePYTHONPATHset?CanyoutrywithavariablesuchasPATH,thatisguaranteedtoexist?Doesitreturnameaningfulvalue?
– Rod
Feb5,2011at19:21
2
PYTHONPATHisusedtoaddnewsearchpathtoPython(sys.path)fromoutsidePython.Havealookatdocs.python.org/using/cmdline.html#environment-variables
– Rod
Feb7,2011at14:41
31
.get()canalsobegivenadefault.
– GringoSuave
Sep21,2018at15:25
|
Show6morecomments
311
Tocheckifthekeyexists(returnsTrueorFalse)
'HOME'inos.environ
Youcanalsouseget()whenprintingthekey;usefulifyouwanttouseadefault.
print(os.environ.get('HOME','/home/username/'))
where/home/username/isthedefault
Share
Improvethisanswer
Follow
editedDec10,2018at2:15
BorisV
10.4k77goldbadges7676silverbadges7979bronzebadges
answeredJul12,2012at8:14
lgriffithslgriffiths
3,25511goldbadge1212silverbadges77bronzebadges
3
4
Whichisbetter,"HOME"inos.environoros.environ.get('HOME')?
– endolith
Feb3,2017at16:11
14
@endolithTheydodifferentthings.ThefirstreturnsTrueorFalse,whilethesecondreturnsavalue,possiblyNone.
– Trenton
Feb13,2018at22:38
3
@endolith,thecorrectquestionwoudbe"HOME"inos.environvsos.environ.get('HOME')isNone.Asyoucanseefirstisfarmorereadable&comfortabletoworkwith.
– KonstantinSekeresh
Oct16,2019at13:43
Addacomment
|
74
Theoriginalquestion(firstpart)was"howtocheckenvironmentvariablesinPython."
Here'showtocheckif$FOOisset:
try:
os.environ["FOO"]
exceptKeyError:
print"PleasesettheenvironmentvariableFOO"
sys.exit(1)
Share
Improvethisanswer
Follow
answeredMar29,2012at13:58
ScottCWilsonScottCWilson
17.7k1010goldbadges5757silverbadges8080bronzebadges
2
5
Trycanbefaster.Thecaseofenvvarsislikelybestfor'try':stackoverflow.com/a/1835844/187769
– RandomInsano
Feb5,2017at16:49
22
@RandomInsanofaster=/=better.Thiscodelookslessreadablethanan"if'FOO'notinos.environ:..."block
– Dangercrow
Oct13,2017at13:27
Addacomment
|
69
Actuallyitcanbedonethisway:
importos
foritem,valueinos.environ.items():
print('{}:{}'.format(item,value))
Orsimply:
fori,jinos.environ.items():
print(i,j)
Forviewingthevalueintheparameter:
print(os.environ['HOME'])
Or:
print(os.environ.get('HOME'))
Tosetthevalue:
os.environ['HOME']='/new/value'
Share
Improvethisanswer
Follow
editedJul25,2021at21:03
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredMar10,2018at15:52
britodfbrbritodfbr
1,4551212silverbadges1616bronzebadges
6
8
No,thisanswerreallydoesn'taddanythingontopoftheexistinganswers
– Bart
May2,2018at10:06
2
Thisshouldberemoved,itisaduplicateofotheranswers.str.formatisjustafancyaddition.
– miike3459
Apr21,2019at16:46
>>>importos,pprint;pprint.pprint(list(os.environ.items()))
– noobninja
May10,2020at18:41
1
Thefirstanswerwithreadableoutputfortheentireenv,thanks.ToviewtheenvinthePyCharmdebugger,Ievaluate{k:vfork,vinsorted(os.environ.items())}
– Noumenon
Aug4,2021at22:55
itaddshowtosetthevalue
– M.C.
Nov26,2021at10:21
|
Show1morecomment
57
Youcanaccesstheenvironmentvariablesusing
importos
printos.environ
TrytoseethecontentofthePYTHONPATHorPYTHONHOMEenvironmentvariables.Maybethiswillbehelpfulforyoursecondquestion.
Share
Improvethisanswer
Follow
editedJul25,2021at20:58
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredFeb5,2011at13:07
andrei1089andrei1089
97855silverbadges88bronzebadges
Addacomment
|
34
Asfortheenvironmentvariables:
importos
printos.environ["HOME"]
Share
Improvethisanswer
Follow
editedJul25,2021at20:58
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredFeb5,2011at13:07
JimBrissomJimBrissom
29.9k33goldbadges3535silverbadges3333bronzebadges
Addacomment
|
30
importos
forainos.environ:
print('Var:',a,'Value:',os.getenv(a))
print("alldone")
Thatwillprintalloftheenvironmentvariablesalongwiththeirvalues.
Share
Improvethisanswer
Follow
editedApr6,2017at8:35
erik.weathers
76011goldbadge77silverbadges1313bronzebadges
answeredMar28,2017at15:46
AzorianAzorian
30133silverbadges22bronzebadges
Addacomment
|
24
Importtheosmodule:
importos
Togetanenvironmentvariable:
os.environ.get('Env_var')
Tosetanenvironmentvariable:
#Setenvironmentvariables
os.environ['Env_var']='SomeValue'
Share
Improvethisanswer
Follow
editedJul25,2021at21:19
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredMay19,2021at9:22
imerlaimerla
1,41922goldbadges99silverbadges1717bronzebadges
Addacomment
|
23
Ifyouareplanningtousethecodeinaproductionwebapplicationcode,usinganywebframeworklikeDjangoandFlask,useprojectslikeenvparse.Usingit,youcanreadthevalueasyourdefinedtype.
fromenvparseimportenv
#willreadWHITE_LIST=hello,world,hitowhite_list=["hello","world","hi"]
white_list=env.list("WHITE_LIST",default=[])
#Perfectforreadingboolean
DEBUG=env.bool("DEBUG",default=False)
NOTE:kennethreitz'sautoenvisarecommendedtoolformakingproject-specificenvironmentvariables.Forthosewhoareusingautoenv,pleasenotetokeepthe.envfileprivate(inaccessibletopublic).
Share
Improvethisanswer
Follow
editedJul25,2021at21:02
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredJan10,2017at4:12
RenjithThankachanRenjithThankachan
3,88611goldbadge2525silverbadges4444bronzebadges
Addacomment
|
14
Therearealsoanumberofgreatlibraries.Envs,forexample,willallowyoutoparseobjectsoutofyourenvironmentvariables,whichisrad.Forexample:
fromenvsimportenv
env('SECRET_KEY')#'your_secret_key_here'
env('SERVER_NAMES',var_type='list')#['your','list','here']
Share
Improvethisanswer
Follow
editedJul25,2021at21:04
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredDec19,2018at16:00
PeterKonnekerPeterKonneker
15311silverbadge77bronzebadges
1
1
Whatdoes"rad"meanin"whichisrad"?rad-"1.(slang)Clippingofradical;excellent"
– PeterMortensen
Jul25,2021at21:06
Addacomment
|
7
Youcanalsotrythis:
First,installpython-decouple
pipinstallpython-decouple
Importitinyourfile
fromdecoupleimportconfig
Thengettheenvironmentvariable
SECRET_KEY=config('SECRET_KEY')
ReadmoreaboutthePythonlibraryhere.
Share
Improvethisanswer
Follow
editedJul25,2021at21:15
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredApr8,2020at15:20
SteveMittoSteveMitto
10311silverbadge55bronzebadges
Addacomment
|
6
Edited-October2021
Following@Peter'scomment,here'showyoucantestit:
main.py
#!/usr/bin/envpython
fromosimportenviron
#Initializevariables
num_of_vars=50
foriinrange(1,num_of_vars):
environ[f"_BENCHMARK_{i}"]=f"BENCHMARKVALUE{i}"
defstopwatch(repeat=1,autorun=True):
"""
Source:https://stackoverflow.com/a/68660080/5285732
stopwatchdecoratortocalculatethetotaltimeofafunction
"""
importtimeit
importfunctools
defouter_func(func):
@functools.wraps(func)
deftime_func(*args,**kwargs):
t1=timeit.default_timer()
for_inrange(repeat):
r=func(*args,**kwargs)
t2=timeit.default_timer()
print(f"Function={func.__name__},Time={t2-t1}")
returnr
ifautorun:
try:
time_func()
exceptTypeError:
raiseException(f"{time_func.__name__}:autorunonlyworkswithnoparameters,youmaywanttouse@stopwatch(autorun=False)")fromNone
returntime_func
ifcallable(repeat):
func=repeat
repeat=1
returnouter_func(func)
returnouter_func
@stopwatch(repeat=10000)
defusing_environ():
foriteminenviron:
pass
@stopwatch
defusing_dict(repeat=10000):
env_vars_dict=dict(environ)
foriteminenv_vars_dict:
pass
python"main.py"
#Output
Function=using_environ,Time=0.216224731
Function=using_dict,Time=0.00014206099999999888
Ifthisistrue...It's1500xfastertouseadict()insteadofaccessingenvirondirectly.
Aperformance-drivenapproach-callingenvironisexpensive,soit'sbettertocallitonceandsaveittoadictionary.Fullexample:
fromosimportenviron
#Slower
print(environ["USER"],environ["NAME"])
#Faster
env_dict=dict(environ)
print(env_dict["USER"],env_dict["NAME"])
P.S-ifyouworryaboutexposingprivateenvironmentvariables,thensanitizeenv_dictaftertheassignment.
Share
Improvethisanswer
Follow
editedOct1,2021at16:10
answeredJan15,2021at0:39
MeirGabayMeirGabay
2,08211goldbadge2020silverbadges2828bronzebadges
1
Thankyou,Peter,I'veupdatedmyanswer
– MeirGabay
Oct1,2021at16:11
Addacomment
|
4
ForDjango,seeDjango-environ.
$pipinstalldjango-environ
importenviron
env=environ.Env(
#setcasting,defaultvalue
DEBUG=(bool,False)
)
#reading.envfile
environ.Env.read_env()
#Falseifnotinos.environ
DEBUG=env('DEBUG')
#RaisesDjango'sImproperlyConfiguredexceptionifSECRET_KEYnotinos.environ
SECRET_KEY=env('SECRET_KEY')
Share
Improvethisanswer
Follow
editedJul25,2021at21:08
PeterMortensen
29.9k2121goldbadges9999silverbadges124124bronzebadges
answeredNov20,2019at15:36
LeonardoLeonardo
19411silverbadge55bronzebadges
1
1
Anexplanationwouldbeinorder.Whatisthecontext-inwhatcontextisthecodeexecuted?OnaserverwithDjango?Locallyfortestingitout?Somewhereelse?Whatistheidea?Whatisthecodesupposedtoaccomplish?
– PeterMortensen
Jul25,2021at21:11
Addacomment
|
1
Youshouldfirstimportosusing
importos
andthenactuallyprinttheenvironmentvariablevalue
print(os.environ['yourvariable'])
ofcourse,replaceyourvariableasthevariableyouwanttoaccess.
Share
Improvethisanswer
Follow
answeredMar14,2021at6:41
ichirodichirod
16511silverbadge33bronzebadges
Addacomment
|
1
Thetrickypartofusingnestedfor-loopsinone-linersisthatyouhavetouselistcomprehension.Soinordertoprintallyourenvironmentvariables,withouthavingtoimportaforeignlibrary,youcanuse:
python-c"importos;L=[f'{k}={v}'fork,vinos.environ.items()];print('\n'.join(L))"
Share
Improvethisanswer
Follow
answeredDec29,2021at20:54
not2qubitnot2qubit
11.8k77goldbadges8282silverbadges110110bronzebadges
Addacomment
|
Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity.
Nottheansweryou'relookingfor?Browseotherquestionstaggedpythonenvironment-variablesoraskyourownquestion.
TheOverflowBlog
Agilitystartswithtrust
WouldyoutrustanAItobeyoureyes?(Ep.437)
FeaturedonMeta
HowmighttheStagingGround&thenewAskWizardworkontheStackExchange...
Shouldweburninatethe[qa]tag?
Overhaulingourcommunity'sclosurereasonsandguidance
Linked
2
Usingsubprocess.callwithanargument
1
CanIreadan`export`edvariablefromapythonscript?
2
settingenvironmentvariableinPythonfrombashwrapper
2
accessingcertainsystem-namefolders(%appdata%)inWindowswithPython
1
Numbaenvironmentvariablenotsetthrough.numba_config.yaml
1
setting$ENV{variable}whencallingpython
0
WebsocketwithpythonBottle+uwsgi|envvars
0
variablefrombatchfiletopython
-2
WorkwithenvironmentvariablesinPython
0
Testifenvvariableisemptyordoesnotexist
Seemorelinkedquestions
Related
6607
HowdoIcheckwhetherafileexistswithoutexceptions?
5664
HowdoIexecuteaprogramorcallasystemcommand?
11990
Whatdoesthe"yield"keyworddo?
7251
DoesPythonhaveaternaryconditionaloperator?
3643
Usingglobalvariablesinafunction
3078
HowdoIpassavariablebyreference?
3251
HowdoIconcatenatetwolistsinPython?
3868
Iteratingoverdictionariesusing'for'loops
936
HowtosetenvironmentvariablesinPython?
2007
HowdoIdeleteanexportedenvironmentvariable?
HotNetworkQuestions
Isanyringoforder15withidentitycommutative?
Whenforgettingstructuredoesn'tmatter
"Audinos"translationproblem
Isresponsibilityforachildbasedongenetics?
DifferencebetweenWesternsanctionsandRussia'schoicetostopoil&gas
HowtoknowwhoboughtthesharesIsold
WhyisEquationofStateofPhotongasdifferentfromtheEquationofStateofBosongas?
InoneofHeinlein'slesser-knownnovels,hedescribedanunusualabilitytodetectmetalobjectswithoutlookingatthem.Whichone?
Whyisfastmatrixmultiplicationimpractical?
Isauthorshipjustifiedforperforminganexperiment7yearsago,whichispublished?Wejustusedsamplesfromthatexperimentforanewanalysis
Doesitmakesensetorepeatedlyincreaseyourlimitorderpriceinsmallincrementsuntilyourorderfills?
Whattypeofmintintzatziki?
Reportpowerifresultisstatisticallysignificant
VectorsperpendiculartoaBeziercurvepath
NuclearArmageddoncomes!CanBob'splantssurvive?
Grammarlyeditingmyeffects,shouldIkeepthemorlistentoGrammerly?
90svampireshortstorysetinpost-communistRomaniahavingasubplotabouttheeffectsofAIDSonvampires
Wouldahollowedoutworldbemechanicallystable?
HowisthenameShivaconnectedwiththeaspectoftheSupremeLord?
Isthereacontradictionbetween2Timothy3:16-17andActs16:6-10?
Asanevaluatorinmathematics,howshouldIgraderesponsesthatanswerthequestionasked,butinlessdetailthandesired?
HarmonicfunctionsoncompleteRiemannianmanifolds
CanyoucarrysomeoneusingLevitatelikeaballoon?
Sailinganage-of-sailsloopwith2-mancrew
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-py
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings