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>Try running:</p>

<pre><code>find . -name \*.pyc -delete
</code></pre>

<p>To delete your <code>.pyc</code> files. </p>

<p>Researching your problem I came across <a href="http://stackoverflow.com/q/26861856/3642398">this question</a>, where a user was experiencing the same thing: <code>.get()</code> seemingly raising a <code>KeyError</code>. In that case, it was caused, according to <a href="http://stackoverflow.com/a/26906934/3642398">this accepted answer</a>, by a <code>.pyc</code> file which contained code where a <code>dict</code> value was being accessed by key (i.e., <code>mydict['potentially_nonexistent_key']</code>), while the traceback was showing the code from the updated <code>.py</code> file where <code>.get()</code> was used. I have never heard of this happening, where the traceback references current code from a <code>.py</code> file, but shows an error raised by an outdated <code>.pyc</code> file, but it seems to have happened at least once in the history of Python...</p>

<p>It is a long shot, but worth a try I thought.</p>

python python-2.7