Skip to content

Commit ae0ea9c

Browse files
committed
Fix the wrong Content-Length in python-server.py for non-ascii characters.
Content-Length is the data in bytes, not len of str. We should use sys.stdin.buffer.read instead of sys.stdin.read to receive bytes. _send_message should calculate "Content-Length" from bytes, not str.
1 parent 2fed954 commit ae0ea9c

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

python_files/python_server.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414

1515

1616
def _send_message(msg: str):
17-
length_msg = len(msg)
17+
# Content-Length is the data size in bytes.
18+
length_msg = len(msg.encode())
1819
STDOUT.buffer.write(f"Content-Length: {length_msg}\r\n\r\n{msg}".encode())
1920
STDOUT.buffer.flush()
2021

@@ -55,10 +56,11 @@ def custom_input(prompt=""):
5556
try:
5657
send_request({"prompt": prompt})
5758
headers = get_headers()
59+
# Content-Length is the data size in bytes.
5860
content_length = int(headers.get("Content-Length", 0))
5961

6062
if content_length:
61-
message_text = STDIN.read(content_length)
63+
message_text = STDIN.buffer.read(content_length).decode()
6264
message_json = json.loads(message_text)
6365
return message_json["result"]["userInput"]
6466
except Exception:
@@ -74,10 +76,11 @@ def handle_response(request_id):
7476
while not STDIN.closed:
7577
try:
7678
headers = get_headers()
79+
# Content-Length is the data size in bytes.
7780
content_length = int(headers.get("Content-Length", 0))
7881

7982
if content_length:
80-
message_text = STDIN.read(content_length)
83+
message_text = STDIN.buffer.read(content_length).decode()
8184
message_json = json.loads(message_text)
8285
our_user_input = message_json["result"]["userInput"]
8386
if message_json["id"] == request_id:
@@ -172,10 +175,11 @@ def get_headers():
172175
while not STDIN.closed:
173176
try:
174177
headers = get_headers()
178+
# Content-Length is the data size in bytes.
175179
content_length = int(headers.get("Content-Length", 0))
176180

177181
if content_length:
178-
request_text = STDIN.read(content_length)
182+
request_text = STDIN.buffer.read(content_length).decode()
179183
request_json = json.loads(request_text)
180184
if request_json["method"] == "execute":
181185
execute(request_json, USER_GLOBALS)

0 commit comments

Comments
 (0)