Python 当我尝试运行它时,我得到以下错误消息:TypeError:ord()应该是一个字符,但找到了长度为0的字符串
已经在许多网站上尝试了许多解决方案Python 当我尝试运行它时,我得到以下错误消息:TypeError:ord()应该是一个字符,但找到了长度为0的字符串,python,python-3.x,Python,Python 3.x,已经在许多网站上尝试了许多解决方案 def get_set_point(self): #returns the current setpoint of serial address = 0x01 command = 0x03 #3 is read register_high = 0x01 register_low = 0x2c #register 300 num_to_read_high = 0x00 num_to_read_lo
def get_set_point(self):
#returns the current setpoint of serial
address = 0x01
command = 0x03 #3 is read
register_high = 0x01
register_low = 0x2c #register 300
num_to_read_high = 0x00
num_to_read_low = 0x01 #only read 1 register
#convert hex values to ASCII string
command = chr(address) + chr(command) + chr(register_high) + chr(register_low) + chr(num_to_read_high) + chr(num_to_read_low)
command += self.calculate_crc(command) #add crc
self._inst.flushInput()
self.write_set('command'.encode('ascii'))
time.sleep(1)
return_list = []
#the correct values are only read 1 at a time; doing read(7) returns junk
#don't know why
for i in range(7):
return_list.append(ord(self.read(1)))
我的阅读功能是:
def read(self, bytes_to_read=None):
if not self._inst:
raise Exception('Tried to read from an instrument that is not connected. See station log for details.')
if bytes and self.instrument_type == SERIAL_INSTRUMENT:
output = self._inst.read(bytes_to_read)
else:
output = self._inst.read()
self.log.debug('[' + self.name + '] <- ' + str(output))
return output
看起来self.read函数不能保证返回请求的字节数。这在文件和设备(如串行连接)中很常见
例如,在CentOS的系统调用手册页中,它说:
On success, the number of bytes read is returned (zero indicates end of
file), and the file position is advanced by this number. It is not an
error if this number is smaller than the number of bytes requested;
this may happen for example because fewer bytes are actually available
right now (maybe because we were close to end-of-file, or because we
are reading from a pipe, or from a terminal), or because read() was
interrupted by a signal.
因此,您的设备可能没有提供任何字节。如果这不是应该发生的,那么您需要调试串行设备。但是,您还应该在Python代码中决定一种处理方法
一些处理方法是:
将空输出处理为NUL,您可以写入ordself.read1或'\x00'。
填充输出。行为类似于1。但是你需要修改self.read的代码。这可以通过打电话来实现
引发一个更合理的异常,例如EOFError,它指示输入流的结束
对于范围7中的i:
字节=self.read1
如果不是字节:
raise EOFError“串行端口未提供输出”
return_list.appendordbyte
你好您能否澄清self.read方法在代码中的作用?在问题中编辑此信息。根据您提供的信息,有迹象表明该方法现在正在返回一个空字符串。在Python2和Python3中对空字符串调用ord的行为将是相同的。请阅读教程并相应地编辑您的问题。ordself1看起来很奇怪。你是说ordself.read1吗?是的,ordself.read1谢谢,我正在尝试与测试仪2007温度箱通信,它显示我已连接,但我认为我无法与设备通信。
On success, the number of bytes read is returned (zero indicates end of
file), and the file position is advanced by this number. It is not an
error if this number is smaller than the number of bytes requested;
this may happen for example because fewer bytes are actually available
right now (maybe because we were close to end-of-file, or because we
are reading from a pipe, or from a terminal), or because read() was
interrupted by a signal.