Linux 但不是 Windows 上的 KeyError
KeyError on Linux but not Windows
我有一个奇怪的情况:
class SomeClass(object):
def __init__(self, data):
self.data = {}
self.data = data
old_data_name = "SOURCE" # self.data[old_data_name] = a list of values
try:
self.data[old_data_name] = [1,2,3,4]
except Exception as e:
print(str(e))
new_data_name = "NEW" # a name
self.data[new_data_name] = numpy.mean(self.data[old_data_name])
所以这段代码在 windows 上完美运行 - 我已经逐条调试并验证了它。
当我将代码部署到 linux 服务器时。它给我一个 KeyError: old_data_name
我确定数据正在到达不应发生密钥错误的地步。
为什么 python 在 Linux 和 Windows 上的表现如此不同?
我的第一印象是版本不匹配:
@Basic Thanks to Basic The issue was indeed version mismatch. Visual
Studio on windows defaulted to 3.6 and Ubuntu was forcing 3.5.2 Din't
know there were such huge breaking changes just from a small revision
from python. Seems like a big mess.
但经过进一步调查。它显示版本 python 3.5.2 与 3.6.6 相比,读取 json 文件的方式很奇怪
从本质上讲,我加载数据的方式意味着它会自引用加载后的属性。例如:
{properties: {"stuff": "do this", "stuff2": "do another with @stuff" }}
我的代码正在查找 stuff2 中的内容,但从未加载内容
Python 版本 3.5.2 没有将 json 数据加载到字典 的特定顺序,这会导致问题。
Python 3.6.6 修复了这个问题。
你不应该在 try-catch 块之外通过 old_data_name
从 self.data
获取值,因为如果没有这样的键你会打印错误而不是试图通过这个键获取一些东西。这是错的。你应该这样写:
class SomeClass(object):
def __init__(self, data):
self.data = {}
self.data = data
old_data_name = "SOURCE" # self.data[old_data_name] = a list of values
try:
self.data[old_data_name] = [1,2,3,4]
new_data_name = "NEW" # a name
self.data[new_data_name] = numpy.mean(self.data[old_data_name])
except Exception as e:
print(str(e))
我有一个奇怪的情况:
class SomeClass(object):
def __init__(self, data):
self.data = {}
self.data = data
old_data_name = "SOURCE" # self.data[old_data_name] = a list of values
try:
self.data[old_data_name] = [1,2,3,4]
except Exception as e:
print(str(e))
new_data_name = "NEW" # a name
self.data[new_data_name] = numpy.mean(self.data[old_data_name])
所以这段代码在 windows 上完美运行 - 我已经逐条调试并验证了它。
当我将代码部署到 linux 服务器时。它给我一个 KeyError: old_data_name
我确定数据正在到达不应发生密钥错误的地步。 为什么 python 在 Linux 和 Windows 上的表现如此不同?
我的第一印象是版本不匹配:
@Basic Thanks to Basic The issue was indeed version mismatch. Visual Studio on windows defaulted to 3.6 and Ubuntu was forcing 3.5.2 Din't know there were such huge breaking changes just from a small revision from python. Seems like a big mess.
但经过进一步调查。它显示版本 python 3.5.2 与 3.6.6 相比,读取 json 文件的方式很奇怪 从本质上讲,我加载数据的方式意味着它会自引用加载后的属性。例如:
{properties: {"stuff": "do this", "stuff2": "do another with @stuff" }}
我的代码正在查找 stuff2 中的内容,但从未加载内容
Python 版本 3.5.2 没有将 json 数据加载到字典 的特定顺序,这会导致问题。
Python 3.6.6 修复了这个问题。
你不应该在 try-catch 块之外通过 old_data_name
从 self.data
获取值,因为如果没有这样的键你会打印错误而不是试图通过这个键获取一些东西。这是错的。你应该这样写:
class SomeClass(object):
def __init__(self, data):
self.data = {}
self.data = data
old_data_name = "SOURCE" # self.data[old_data_name] = a list of values
try:
self.data[old_data_name] = [1,2,3,4]
new_data_name = "NEW" # a name
self.data[new_data_name] = numpy.mean(self.data[old_data_name])
except Exception as e:
print(str(e))