Skip to content

Commit e0d9072

Browse files
shunyishunyi
authored andcommitted
A quick, trivial yet not beautiful patch for issue_command
+ Determine the Python version of current environment + Deal with the args according to py2 or py3
1 parent 955577d commit e0d9072

1 file changed

Lines changed: 47 additions & 4 deletions

File tree

webkit_server.py

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@
1313
SERVER_EXEC = os.path.abspath(os.path.join(os.path.dirname(__file__),
1414
'webkit_server'))
1515

16+
if sys.version_info[0] == 2:
17+
PY2 = True
18+
PY3 = False
19+
elif sys.version_info[0] == 3:
20+
PY2 = False
21+
PY3 = True
22+
1623

1724
class SelectionMixin(object):
1825
""" Implements a generic XPath selection for a class providing
@@ -513,12 +520,47 @@ def issue_command(self, cmd, *args):
513520
self._writeline(cmd)
514521
self._writeline(str(len(args)))
515522
for arg in args:
516-
arg = str(arg)
517-
self._writeline(str(len(arg)))
518-
self._sock.sendall(arg.encode("utf-8"))
523+
self.send_arg(arg)
519524

520525
return self._read_response()
521526

527+
def send_arg(self, arg):
528+
""" Send each arg for args in issue_command """
529+
arg = self.prepare_for_socket_sendall(arg)
530+
self._writeline(str(len(arg)))
531+
self._sock.sendall(arg)
532+
533+
def prepare_for_socket_sendall(self, arg):
534+
""" Deal with the unicode and bytes problem in Python 2 and Python 3 for socket.sendall """
535+
536+
if PY2:
537+
if type(arg) != unicode:
538+
try:
539+
arg = str(arg)
540+
except:
541+
pass
542+
543+
# socket.sendall in Python 2 accepts str (bytes)
544+
if type(arg) not in (str, unicode):
545+
raise TypeError("type({}) should be str (bytes) or unicode, not {}".format(arg, type(arg)))
546+
elif type(arg) == unicode:
547+
arg = arg.encode("utf-8")
548+
549+
if PY3:
550+
if type(arg) != bytes:
551+
try:
552+
arg = str(arg)
553+
except:
554+
pass
555+
556+
# socket.sendall in Python 3 accepts bytes
557+
if type(arg) not in (str, bytes):
558+
raise TypeError("type({}) should be str or bytes, not {}".format(arg, type(arg)))
559+
elif type(arg) == str:
560+
arg = arg.encode("utf-8")
561+
562+
return arg
563+
522564
def _read_response(self):
523565
""" Reads a complete response packet from the server """
524566
result = self.buf.read_line().decode("utf-8")
@@ -538,4 +580,5 @@ def _read_message(self):
538580

539581
def _writeline(self, line):
540582
""" Writes a line to the underlying socket. """
541-
self._sock.sendall(line.encode("utf-8") + b"\n")
583+
line = self.prepare_for_socket_sendall(line)
584+
self._sock.sendall(line + b"\n")

0 commit comments

Comments
 (0)