unsupported operand type(s) for %: 'bytes' and 'str'

非 Y 不嫁゛ 提交于 2020-01-17 04:25:11

问题


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)

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

worked fine, the problem only occurred when i try to use the result of the input as a string to include in ser.write

A bit more of the code:

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.


回答1:


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?

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

Exmaple -

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

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




回答2:


The left hand argument to % should be a string, but you have passed b"%d\r\n" which is a byte literal.

Suggest replacement with

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



回答3:


In Python 3 you should use the string format function:

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

This works for bytes in Python 3.5 (see link).



来源:https://stackoverflow.com/questions/31213086/unsupported-operand-types-for-bytes-and-str

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!