【问题标题】:unsupported operand type(s) for %: 'bytes' and 'str'% 不支持的操作数类型:“bytes”和“str”
【发布时间】:2015-07-03 19:22:24
【问题描述】:

我收到以下行中的错误:

 command = input("please type command.example open 1")
        #call the serial_connection() function
        ser.write(b"%d\r\n"%command)

本质上我想要用户写的输入并解析成ser.write,不要求输入直接将字符串放入ser.write如:

ser.write(b'close1\r\n')

工作正常,仅当我尝试将输入结果作为字符串包含在 ser.write 中时才会出现问题

更多代码:

ser = 0

#Initialize Serial Port
def serial_connection():
    COMPORT = int(input("Please enter the port number: "))
    ser = serial.Serial()
    ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program must be at same rate
    ser.port = COMPORT - 1 #counter for port name starts at 0

    #check to see if port is open or closed
    if not ser.isOpen():
        print ('The Port %d is open - Will attempt to close lock 1 Stephan: '%COMPORT + ser.portstr)
        #timeout in seconds
        ser.timeout = 10
        ser.open()
        command = input("please type command.example open 1")
        #call the serial_connection() function
        ser.write(b"%d\r\n"%command)

    else:
        print ('The Port %d is **open** Stephan' %COMPORT)

如有任何澄清,请提出建议。

【问题讨论】:

    标签: python python-3.x serial-port hardware pyserial


    【解决方案1】:

    % 的左侧参数应该是一个字符串,但您传递了 b"%d\r\n" 这是一个字节文字。

    建议替换为

    ser.write(("%d\r\n" % command).encode("ascii"))
    

    【讨论】:

      【解决方案2】:

      也许你可以先尝试解码字节字符串(如果它不是一个常量字符串,否则就从普通字符串开始),然后应用格式,然后再编码回来?

      另外,您应该使用%s 而不是%d,因为您的` 命令是来自用户的直接输入,它是一个字符串。

      示例 -

      ser.write(("%s\r\n"%command).encode())
      

      如果您不传递任何参数,则默认为当前系统默认编码,您还可以指定要使用的编码,例如 utf-8ascii 等。示例 - ser.write(("%s\r\n"%command).encode('utf-8'))ser.write(("%s\r\n"%command).encode('ascii'))

      【讨论】:

      • 感谢您的建议。我得到以下错误: ser.write(("%d\r\n"%command).encode()) TypeError: %d format: a number is required, not str
      • 如果是 str,使用 - %s。更新答案。
      • 很高兴我能帮上忙
      【解决方案3】:

      在 Python 3 中你应该使用字符串格式化函数:

      ser.write(b"{0}\r\n".format(command))
      

      这适用于 Python 3.5 中的字节(请参阅 link)。

      【讨论】:

      • 对于 Python 3.4,您可以考虑使用字符串连接函数 b", ".join([b'1', b'2', b'3'])
      • 感谢您的建议,我不幸收到以下错误:ser.write(b"{0}\r\n".format(command)) AttributeError: 'bytes' object has no attribute '格式'
      • 是的——你是对的。由于 PySerial 只接受字节输入,而 Python 3.4 对字符串使用 Unicode 默认值,因此您必须编码为 ASCII。
      猜你喜欢
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-20
      • 2018-12-06
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多