Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用从串行设备读取的字符串时出现字典键错误_Python_Dictionary_Keyerror - Fatal编程技术网

Python 使用从串行设备读取的字符串时出现字典键错误

Python 使用从串行设备读取的字符串时出现字典键错误,python,dictionary,keyerror,Python,Dictionary,Keyerror,我正在阅读Python字典的关键序列数据。当我读取串行数据时,它以字节流的形式通过,我将其转换为字符串。当我使用该字符串搜索字典键时,我得到一个keyrerror 我试图通过手动输入键来搜索同一个键,这将完美地返回值。我的代码如下,感谢您的帮助 plates_id = {'TestCylinder100umHard': 8, 'TestCube100umHard': 7, 'MotorMount100umHard': 6, 'InnerShaft100umHard': 5, 'DriveSlee

我正在阅读Python字典的关键序列数据。当我读取串行数据时,它以字节流的形式通过,我将其转换为字符串。当我使用该字符串搜索字典键时,我得到一个keyrerror

我试图通过手动输入键来搜索同一个键,这将完美地返回值。我的代码如下,感谢您的帮助

plates_id = {'TestCylinder100umHard': 8, 'TestCube100umHard': 7, 'MotorMount100umHard': 6, 'InnerShaft100umHard': 5, 'DriveSleeve100umHard': 4, 'DrivePulley100umHard': 3, 'BearingSleeve100umHard': 2, 'Quad': 1, 'Auto Calibration Plate': 0}

s_bytes_new = ser.inWaiting()
s_new = str(ser.read(s_bytes_new))
printing_plate = plates_id[s_new]
print(printing_plate)
这就产生了这个错误:

Traceback (most recent call last):
  File "C:/pythonProjects/nanoDLP/touchInterface/printTest.py", line 66, in <module>
  printing_plate = plates_id[s_new]
KeyError: "'Auto Calibration Plate'"
回溯(最近一次呼叫最后一次):
文件“C:/pythonProjects/nanoDLP/touchInterface/printTest.py”,第66行,在
印版=印版id[s\U new]
键错误:“‘自动校准板’”
如果你需要更多信息,请告诉我。谢谢

Dylan使用.decode()代替str将字节转换为str

s_new  = ser.read(s_bytes_new).decode()
使用.decode()代替str,将字节转换为str

s_new  = ser.read(s_bytes_new).decode()

你调试过printed
repr(s_new)
以查看是否有一些隐藏的空格字符并尝试将其剥离:
s_new=s_new.strip()
?你调试过printed
repr(s_new)
以查看是否有一些隐藏的空格字符并尝试将其剥离:
s_new=s_new.strip()
?哇,这是一个简单的修复方法!非常感谢。哇,这是一个简单的解决办法!非常感谢。