Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os.environ throws key error?

I'm accessing an environment variable in a script with os.environ.get and it's throwing a KeyError. 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.

What is going on?

$ python score.py Traceback (most recent call last):   File "score.py", line 4, in <module>     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')" $ 

As requested, here's the source code for score.py

from __future__ import print_function  from log import get_logger, setup_logging setup_logging() log = get_logger('score') 

And here's log.py

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) 
like image 801
Chris B. Avatar asked Sep 01 '16 20:09

Chris B.


People also ask

Why am I getting a key error in Python?

A Python KeyError occurs when you attempt to access an item in a dictionary that does not exist using the indexing syntax. This error is raised because Python cannot return a value for an item that does not exist in a dictionary. The keys are “name”, “price”, and “RAM”.

What does OS environ do in Python?

environ in Python is a mapping object that represents the user's environmental variables. It returns a dictionary having user's environmental variable as key and their values as value.

How do you fix KeyError 0?

The Python "KeyError: 0" exception is caused when we try to access a 0 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.

How do I set an environment variable in Python?

To permanently modify the default environment variables, click Start and search for 'edit environment variables', or open System properties, Advanced system settings and click the Environment Variables button. In this dialog, you can add or modify User and System variables.


1 Answers

Try running:

find . -name \*.pyc -delete 

To delete your .pyc files.

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

It is a long shot, but worth a try I thought.

like image 181
elethan Avatar answered Sep 28 '22 03:09

elethan