Skip to content

Commit

Permalink
python: Deal with str and byte differences.
Browse files Browse the repository at this point in the history
Python 3 has separate types for strings and bytes.  Python 2 used the
same type for both.  We need to convert strings to bytes before writing
them out to a socket.  We also need to convert data read from the socket
to a string.

Signed-off-by: Russell Bryant <russell@ovn.org>
Acked-by: Ben Pfaff <blp@ovn.org>
  • Loading branch information
russellb committed Feb 2, 2016
1 parent fbafc3c commit 0e7c46c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions python/ovs/jsonrpc.py
Expand Up @@ -264,6 +264,15 @@ def recv(self):
while True:
if not self.input:
error, data = self.stream.recv(4096)
# Python 3 has separate types for strings and bytes. We
# received bytes from a socket. We expect it to be string
# data, so we convert it here as soon as possible.
if (data and not error
and not isinstance(data, six.string_types)):
try:
data = data.decode('utf-8')
except UnicodeError:
error = errno.EILSEQ
if error:
if error == errno.EAGAIN:
return error, None
Expand Down
3 changes: 3 additions & 0 deletions python/ovs/socket_util.py
Expand Up @@ -19,6 +19,7 @@
import socket
import sys

import six
from six.moves import range

import ovs.fatal_signal
Expand Down Expand Up @@ -275,6 +276,8 @@ def write_fully(fd, buf):
bytes_written = 0
if len(buf) == 0:
return 0, 0
if sys.version_info[0] >= 3 and not isinstance(buf, six.binary_type):
buf = six.binary_type(buf, 'utf-8')
while True:
try:
retval = os.write(fd, buf)
Expand Down
6 changes: 6 additions & 0 deletions python/ovs/stream.py
Expand Up @@ -15,6 +15,7 @@
import errno
import os
import socket
import sys

import six

Expand Down Expand Up @@ -223,6 +224,11 @@ def send(self, buf):
return 0

try:
# Python 3 has separate types for strings and bytes. We must have
# bytes here.
if (sys.version_info[0] >= 3
and not isinstance(buf, six.binary_type)):
buf = six.binary_type(buf, 'utf-8')
return self.socket.send(buf)
except socket.error as e:
return -ovs.socket_util.get_exception_errno(e)
Expand Down

0 comments on commit 0e7c46c

Please sign in to comment.