简体   繁体   中英

how to use os.environ as a dictionary value

Having some issues creating a dictionzry which should contain an env variable as a value per key. It's the single quotes that are causing the problem I guess. Could someone point me to a pythonic way of doing this ? :)

macros = {
   'date': os.environ['NOTIFY_SHORTDATETIME'],
   'hostname': os.environ['NOTIFY_HOSTNAME'],
   'ip': os.environ['NOTIFY_HOSTADDRESS'],
   'alias': os.environ['NOTIFY_HOSTALIAS'],
   'hostcmd': os.environ['NOTIFY_HOSTCHECKCOMMAND'],
   'servicecmd': os.environ['NOTIFY_SERVICECHECKCOMMAND'],
   'servicenotifnum': os.environ['NOTIFY_SERVICENOTIFICATIONNUMBER'],
   'servicedesc': os.environ['NOTIFY_SERVICEDESC'],
   'hostoutput': os.environ['NOTIFY_HOSTOUTPUT'],
   'serviceoutput': os.environ['NOTIFY_SERVICEOUTPUT'],
   'hoststate': os.environ['NOTIFY_HOSTSTATE'],
   'svcstate': os.environ['NOTIFY_SERVICESTATE'],
   'lasthoststate': os.environ['NOTIFY_LASTHOSTSTATE'],
   'laststatesvc': os.environ['NOTIFY_LASTSTATESERVICE'],
   'notiftype': os.environ['NOTIFY_NOTIFICATIONTYPE'],
}

Key Error means that the named item does not exist in the os.environ . If you are trying to find out what does exist on your machine, you can debug and print out the list like:

import os
for k in os.environ:
  print k

On my Windows XP box, I get these output:

TMP
COMPUTERNAME
USERDOMAIN
PSMODULEPATH
COMMONPROGRAMFILES
PROCESSOR_IDENTIFIER
PROGRAMFILES
PROCESSOR_REVISION
SYSTEMROOT
PATH
PROGRAMFILES(X86)
COMSPEC
TEMP
COMMONPROGRAMFILES(X86
PROCESSOR_ARCHITECTURE
ALLUSERSPROFILE
LOCALAPPDATA
HOMEPATH
UATDATA
VS120COMNTOOLS
PROGRAMW6432
USERNAME
LOGONSERVER
PROMPT
SESSIONNAME
PROGRAMDATA
USERDNSDOMAIN
PATHEXT
FP_NO_HOST_CHECK
WINDIR
APPDATA
HOMEDRIVE
SYSTEMDRIVE
NUMBER_OF_PROCESSORS
VBOX_INSTALL_PATH
PROCESSOR_LEVEL
PROCESSOR_ARCHITEW6432
COMMONPROGRAMW6432
OS
PUBLIC
USERPROFILE

Based on the error you're getting, it seems that you're trying to use environment variables for a different operating system than whatever you're actually using. You should resolve this by referring to the correct OS environment variables for your computer.

You can wrap os.environ with dict()

Python3 example:

In [1]: import os

In [2]: os.environ.clear()

In [3]: os.environ
Out[3]: environ{}

In [4]: os.environ['FOO']='bar'

In [5]: os.environ
Out[5]: environ{'FOO': 'bar'}

In [6]: type(os.environ)
Out[6]: os._Environ

In [7]: type(dict(os.environ))
Out[7]: dict

In [8]: foo = dict(os.environ)

In [9]: foo['FOO']
Out[9]: 'bar'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM