pyserial ser.write('string') TypeError in OS X


R

Rodrigo

Maybe this is not a bug at all, but i have installed python2.5. 3.01
and 3.1.1. In python 2.5 ser. write('this is a string') works just
fine.
On the other hand, with 3.01 and 3.1.1 (pyserial 2.5 rc1) when i do a
ser.write('this is a string') i get the following error"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/
python3.1/site-packages/serial/serialposix.py", line 466, in write
raise TypeError('expected %s or bytearray, got %s' % (bytes, type
(data)))
TypeError: expected <class 'bytes'> or bytearray, got <class 'str'>

I honestly dont get what im doing wrong here

any feedback much appreciated

regards
r
 
Ad

Advertisements

D

Diez B. Roggisch

Rodrigo said:
Maybe this is not a bug at all, but i have installed python2.5. 3.01
and 3.1.1. In python 2.5 ser. write('this is a string') works just
fine.
On the other hand, with 3.01 and 3.1.1 (pyserial 2.5 rc1) when i do a
ser.write('this is a string') i get the following error"

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.1/lib/
python3.1/site-packages/serial/serialposix.py", line 466, in write
raise TypeError('expected %s or bytearray, got %s' % (bytes, type
(data)))
TypeError: expected <class 'bytes'> or bytearray, got <class 'str'>

I honestly dont get what im doing wrong here

In Python3, the standard type for string-literals is not a byte-string,
but unicode. Thus you need to explicitly encode the passed value to a
bytes-object, as that's what is allowd for communicating with the
uoutside world.


ser.write('this is a string'.encode('utf-8'))

should do the trick.

The error-message is an abomination though...

Diez
 
Ad

Advertisements

G

Gabriel Genellina

Maybe this is not a bug at all, but i have installed python2.5. 3.01
and 3.1.1. In python 2.5 ser. write('this is a string') works just
fine.
On the other hand, with 3.01 and 3.1.1 (pyserial 2.5 rc1) when i do a
ser.write('this is a string') i get the following error"

TypeError: expected <class 'bytes'> or bytearray, got <class 'str'>

Try with ser.write(b'this is a string')

Python 3.0 introduced many changes, one of them is to work with unicode by
default. "abc" used to be a string (of bytes) in 2.x, and u"abc" unicode
text. With Python 3.x, "abc" is unicode (spelled just `str` now) and
b"abc" denotes the `bytes` type (the old str). bytearray is a mutable
variant of the bytes type.

Read the "What's new" document for the 3.0 release:
http://www.python.org/doc/3.0.1/whatsnew/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top