%不支持的操作数类型:“字节"和"STR" [英] unsupported operand type(s) for %: 'bytes' and 'str'

查看:95
本文介绍了%不支持的操作数类型:“字节"和"STR"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下行中收到错误:

I receive the error in the following line:

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

基本上,我希望由用户编写输入并将其解析为ser.write,而不要求输入并将字符串直接放入ser.write中,例如:

Essentially I want the input written by the user and parse it into ser.write, without asking for the input and directly putting the string into ser.write such as:

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

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

worked fine, the problem only occurred when i try to use the result of the input as a string to include in 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)

如有任何澄清,请告知.

for any clarification, kindly advise.

推荐答案

也许您可以先尝试解码字节字符串(如果它不是常量字符串,否则就以普通字符串开头),然后应用格式,然后对其进行编码回来吗?

Maybe you can try decoding byte string first (if its not a constant string, otherwise just start with normal string), then applying the format, and then encoding it back?

此外,您应该使用%s而不是%d,因为您的命令是用户直接输入的字符串.

Also, you should use %s instead of %d because your` command is a direct input from user, which is a string.

例如-

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'))

If you do not pass any arguments , it defaults to current system default encoding, you can also specify an encoding to use such as utf-8 or ascii , etc. Example of that - ser.write(("%s\r\n"%command).encode('utf-8')) or ser.write(("%s\r\n"%command).encode('ascii'))

这篇关于%不支持的操作数类型:“字节"和"STR"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆