Python os.environ 抛出关键错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39280435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python os.environ throws key error?
提问by Chris B.
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.
我正在使用脚本访问环境变量os.environ.get
,它抛出一个KeyError
. 它不会从 Python 提示中抛出错误。它在 OS X 10.11.6 上运行,并且是 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
根据要求,这里是源代码 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
这是 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)
采纳答案by elethan
Try running:
尝试运行:
find . -name \*.pyc -delete
To delete your .pyc
files.
删除您的.pyc
文件。
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...
研究你的问题我遇到了这个问题,其中一个用户遇到了同样的事情:.get()
似乎提高了一个KeyError
. 在那种情况下,根据这个接受的答案,它是由一个.pyc
包含代码的文件引起的,其中一个dict
值正在被键(即,mydict['potentially_nonexistent_key']
)访问,而回溯显示来自更新.py
文件的代码.get()
被使用。我从未听说过这种情况,回溯引用了.py
文件中的当前代码,但显示了由过时.pyc
文件引发的错误,但它似乎在 Python 的历史中至少发生过一次......
It is a long shot, but worth a try I thought.
这是一个远景,但我认为值得一试。
回答by Israel
Command for windows to delete the .pyc files:
Windows 删除 .pyc 文件的命令:
del /S *.pyc
回答by tomdaq
I encountered a similar error when I set the environment variable without exporting it. So if you do this:
我在设置环境变量而不导出它时遇到了类似的错误。所以如果你这样做:
me@host:/# NODE_ENV=foo
You will get this:
你会得到这个:
me@host:/# python3
Python 3.8.2 (default, Apr 27 2020, 15:53:34)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> node_env = os.environ['NODE_ENV']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.8/os.py", line 675, in __getitem__
raise KeyError(key) from None
KeyError: 'NODE_ENV'
>>>
But if you do this:
但如果你这样做:
me@host:/# NODE_ENV=foo
me@host:/# export NODE_ENV
It works:
有用:
me@host:/# python3
Python 3.8.2 (default, Apr 27 2020, 15:53:34)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> node_env = os.environ['NODE_ENV']
>>> print(node_env)
foo
>>>
回答by BPL
I'd recommend you start debugging os.py, for instance, on windows it's being used this implementation:
我建议你开始调试 os.py,例如,在 Windows 上它正在使用这个实现:
def get(self, key, failobj=None):
print self.data.__class__
print key
return self.data.get(key.upper(), failobj)
And if I test it with this:
如果我用这个测试它:
import os
try:
os.environ.get('NODE_ENV')
except Exception as e:
print("-->{0}".format(e.__class__))
os.environ['NODE_ENV'] = "foobar"
try:
os.environ.get('NODE_ENV')
except Exception as e:
print("{0}".format(e.__class__))
The output will be:
输出将是:
<type 'dict'>
PYTHONUSERBASE
<type 'dict'>
APPDATA
<type 'dict'>
NODE_ENV
<type 'dict'>
NODE_ENV
So it makes sense the exception is not spawned reading dict.getdocs.
因此,在阅读dict.get文档时不会产生异常是有道理的。
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 NODE_ENV
. And if all that don't work, restart your terminal to clear up.
无论如何,如果你不想搞砸或调试python模块,请尝试清理*.pyc文件,尝试正确设置NODE_ENV
。如果所有这些都不起作用,请重新启动终端以进行清理。