summaryrefslogtreecommitdiff
path: root/serial/serialutil.py
diff options
context:
space:
mode:
authorcliechti <cliechti@f19166aa-fa4f-0410-85c2-fa1106f25c8a>2013-10-16 02:57:27 +0000
committercliechti <cliechti@f19166aa-fa4f-0410-85c2-fa1106f25c8a>2013-10-16 02:57:27 +0000
commitf911f1be9b07d0489f4e51c8d39e277c552ed9ae (patch)
tree8fe7d9de8d4bb052d04d75db64c05aa59cf9f2a3 /serial/serialutil.py
parent6a5185b55c57f56abe67cead08925ac78fb1830b (diff)
downloadpyserial-f911f1be9b07d0489f4e51c8d39e277c552ed9ae.tar.gz
Ensure working with bytes in write() calls. to_bytes() extended to handle bytes and memoryview instaces
git-svn-id: http://svn.code.sf.net/p/pyserial/code/trunk/pyserial@479 f19166aa-fa4f-0410-85c2-fa1106f25c8a
Diffstat (limited to 'serial/serialutil.py')
-rw-r--r--serial/serialutil.py33
1 files changed, 27 insertions, 6 deletions
diff --git a/serial/serialutil.py b/serial/serialutil.py
index a8f0716..f575963 100644
--- a/serial/serialutil.py
+++ b/serial/serialutil.py
@@ -46,14 +46,35 @@ except (NameError, AttributeError):
other = bytearray(other)
return list.__eq__(self, other)
-# all Python versions prior 3.x convert str([17]) to '[17]' instead of '\x11'
-# so a simple bytes(sequence) doesn't work for all versions
+# ``memoryview`` was introduced in Python 2.7 and ``bytes(some_memoryview)``
+# isn't returning the contents (very unfortunate). Therefore we need special
+# cases and test for it. Ensure that there is a ``memoryview`` object for older
+# Python versions. This is easier than making every test dependent on its
+# existence.
+try:
+ memoryview
+except (NameError, AttributeError):
+ # implementation does not matter as we do not realy use it.
+ # it just must not inherit from something else we might care for.
+ class memoryview:
+ pass
+
+
+# all Python versions prior 3.x convert ``str([17])`` to '[17]' instead of '\x11'
+# so a simple ``bytes(sequence)`` doesn't work for all versions
def to_bytes(seq):
"""convert a sequence to a bytes type"""
- b = bytearray()
- for item in seq:
- b.append(item) # this one handles int and str
- return bytes(b)
+ if isinstance(seq, bytes):
+ return seq
+ elif isinstance(seq, bytearray):
+ return bytes(seq)
+ elif isinstance(seq, memoryview):
+ return seq.tobytes()
+ else:
+ b = bytearray()
+ for item in seq:
+ b.append(item) # this one handles int and str
+ return bytes(b)
# create control bytes
XON = to_bytes([17])