Python os.environ throws key error?
<p>I'm accessing an environment variable in a script with <code>os.environ.get</code> and it's throwing a <code>KeyError</code>. It doesn't throw the error from the Python prompt. This is running on OS X 10.11.6, and is Python 2.7.10.</p>

<p>What is going on?</p>

<pre><code>$ python score.py
Traceback (most recent call last):
  File "score.py", line 4, in &lt;module&gt;
    setup_logging()
  File "/score/log.py", line 29, in setup_logging
    config = get_config()
  File "/score/log.py", line 11, in get_config
    environment = os.environ.get('NODE_ENV')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'NODE_ENV'
$ python -c "import os; os.environ.get('NODE_ENV')"
$
</code></pre>

<p><strong>As requested, here's the source code for <code>score.py</code></strong></p>

<pre><code>from __future__ import print_function

from log import get_logger, setup_logging
setup_logging()
log = get_logger('score')
</code></pre>

<p><strong>And here's <code>log.py</code></strong></p>

<pre><code>import json
import os
import sys

from iron_worker import IronWorker
from logbook import Logger, Processor, NestedSetup, StderrHandler, SyslogHandler

IRON_IO_TASK_ID = IronWorker.task_id()

def get_config():
  environment = os.environ.get('NODE_ENV')
  if environment == 'production':
    filename = '../config/config-production.json'
  elif environment == 'integration':
    filename = '../config/config-integration.json'
  else:
    filename = '../config/config-dev.json'

  with open(filename) as f:
    return json.load(f)

def setup_logging():
  # This defines a remote Syslog handler
  # This will include the TASK ID, if defined
  app_name = 'scoreworker'
  if IRON_IO_TASK_ID:
    app_name += '-' + IRON_IO_TASK_ID

  config = get_config()

  default_log_handler = NestedSetup([
    StderrHandler(),
    SyslogHandler(
      app_name,
      address = (config['host'], config['port']),
      level = 'ERROR',
      bubble = True
    )
  ])
  default_log_handler.push_application()

def get_logger(name):
  return Logger(name)
</code></pre>

<p>I'd recommend you start debugging os.py, for instance, on windows it's being used this implementation:</p>

<pre><code>def get(self, key, failobj=None):
    print self.data.__class__
    print key
    return self.data.get(key.upper(), failobj)
</code></pre>

<p>And if I test it with this:</p>

<pre><code>import os


try:
    os.environ.get('NODE_ENV')
except Exception as e:
    print("--&gt;{0}".format(e.__class__))

os.environ['NODE_ENV'] = "foobar"

try:
    os.environ.get('NODE_ENV')
except Exception as e:
    print("{0}".format(e.__class__))
</code></pre>

<p>The output will be:</p>

<pre><code>&lt;type 'dict'&gt;
PYTHONUSERBASE
&lt;type 'dict'&gt;
APPDATA
&lt;type 'dict'&gt;
NODE_ENV
&lt;type 'dict'&gt;
NODE_ENV
</code></pre>

<p>So it makes sense the exception is not spawned reading <a href="https://docs.python.org/2/library/stdtypes.html#dict.get" rel="nofollow">dict.get</a> docs.</p>

<p>In any case, if you don't want to mess up or debugging the python modules, try cleaning up the *.pyc files, try to set up properly <code>NODE_ENV</code>. And if all that don't work, restart your terminal to clear up.</p>

python python-2.7