连接字节时出现类型错误



我遇到了字节编码问题,希望得到帮助,请卡住(python初学者,试图将一些代码从github改编为python3)。我"认为"问题是我需要将"data"变量编码为字节,但是由于 .encode() 不起作用,我正在努力做到这一点。返回的错误是:

Traceback (most recent call last):
  File "C:/Users/DR/Desktop/iqfeed3.py", line 51, in <module>
    data = read_historical_data_socket(sock)
  File "C:/Users/DR/Desktop/iqfeed3.py", line 21, in read_historical_data_socket
    buffer += data
TypeError: can only concatenate str (not "bytes") to str

底层代码(尝试缓冲股票价格数据并写入csv)如下(突出显示第21行和第51行并带有注释):

# iqfeed3.py
import sys
import socket
# iqfeed3.py
def read_historical_data_socket(sock, recv_buffer=4096):
    """
    Read the information from the socket, in a buffered
    fashion, receiving only 4096 bytes at a time.
    Parameters:
    sock - The socket object
    recv_buffer - Amount in bytes to receive per read
    """
    buffer = ""
    data = ""
    while True:
        data = sock.recv(recv_buffer)
        buffer += data #TRACEBACK ERROR LINE 21
        # Check if the end message string arrives
        if "!ENDMSG!" in buffer:
            break
    # Remove the end message string
    buffer = buffer[:-12]
    return buffer
if __name__ == "__main__":
    # Define server host, port and symbols to download
    host = "127.0.0.1"  # Localhost
    port = 9100  # Historical data socket port
    syms = ["AAPL", "GOOG", "AMZN"]
    # Download each symbol to disk
    for sym in syms:
        print ("Downloading symbol: %s..." % sym)
        # Construct the message needed by IQFeed to retrieve data
        message = "HIT,%s,60,20180601 075000,,,093000,160000,1n" % sym
        # Open a streaming socket to the IQFeed server locally
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        # Send the historical data request
        # message and buffer the data
        sock.sendall(message.encode()) #Formerly gave error "TypeError: a bytes-like object is required, not 'str'" before adding .encode()
        data = read_historical_data_socket(sock) #TRACEBACK ERROR LINE 51
        sock.close
        # Remove all the endlines and line-ending
        # comma delimiter from each record
        data = "".join(data.split("r"))
        data = data.replace(",n","n")[:-1]
        # Write the data stream to disk
        f = open("%s.csv" % sym, "w")
        f.write(data)
        f.close()

提前感谢您的任何帮助或指示。

院长

你混淆了字符串和原始字节。您的buffer是一个字符串,而套接字输入通常是bytes

最好的方法是简单地将接收到的字节转换为字符串。

试试这个代码:

data = sock.recv(recv_buffer)
buffer += data.decode()

这将使用默认utf-8编码。如果需要另一个,请显式指定。

相关内容

最新更新