我在遇到字节编码问题时遇到问题,希望一直坚持下去(Python初学者,试图将一些代码从github改编为python3)。我“认为”问题是我需要将“数据”变量编码为字节,但是由于.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,1\n" % 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()
在此先感谢您的帮助或指示。
迪恩
答案 0 :(得分:3)
您正在混淆字符串和原始字节。您的buffer
是一个字符串,而套接字输入通常是bytes
。
最好的方法是将接收到的字节转换为字符串。
尝试以下代码:
data = sock.recv(recv_buffer)
buffer += data.decode()
这将使用默认的utf-8
编码。如果需要另一个,请明确指定。