Python3中的Traceback:TypeError:ord()期望的字符串长度为1,但找到了int

时间:2018-11-01 23:57:04

标签: python-3.4

我正在尝试控制电源。

json.dump(json_data, outfile, separators=(',', ':'))

运行此命令后得到的输出和回溯是:

设置为远程命令:

aa úú 20 01 úú

úú úú úú úú úú

úú úú úú úú úú

úú úú úú úú úú

úú úú úú úú úú

cb

响应:

# Set power supply to remote mode.
import serial
length_packet = 26 # Number of bytes in a packet
nl = "\n"


def DumpCommand(bytes):
    assert(len(bytes) == length_packet)
    header = " "*3
    print (header)
    for i in range(length_packet):
        if i % 10 == 0 and i != 0:
            print (nl + header)
        if i % 5 == 0:
            print (" ")
        s = "%02x" % ord(bytes[i])
        if s == "00":
            s = chr(250)*2
        print (s)


def CalculateChecksum(cmd):
    assert((len(cmd) == length_packet - 1) or (len(cmd) == length_packet))
    checksum = 0
    for i in range(length_packet - 1):
        checksum += ord(cmd[i])
    checksum %= 256
    return checksum

def main():

    port = 'COM8'
    baudrate = 9600
    sp = serial.Serial(port, baudrate) # Open a serial connection

# Construct a set to remote command
    cmd = chr(0xaa) + chr(0x00) + chr(0x20) # First three bytes
    cmd += chr(0x01) + chr(0x00)*(length_packet - 1 - 4)
    cmd += chr(CalculateChecksum(cmd))
    assert(len(cmd) == length_packet)

# Send command to power supply
    sp.write(cmd.encode())
    print ("Set to remote command:")
    DumpCommand(cmd)

# Get response from power supply
    response = sp.read(length_packet)
    assert(len(response) == length_packet)
    print ("Response:")
    DumpCommand(response)

main()

这段代码最初是用Python2编写的,现在我正在使用Python3。预期的输出是:

Traceback (most recent call last):
  File "powr_sup_trial.py", line 48, in <module>
    main()
  File "powr_sup_trial.py", line 47, in main
    DumpCommand(response)
  File "powr_sup_trial.py", line 15, in DumpCommand
    s = "%02x" % ord(bytes[i])
TypeError: ord() expected string of length 1, but int found

0 个答案:

没有答案