PySerial for Python 2 vs. Python 3

Terry Reedy tjreedy at udel.edu
Wed Jan 1 14:54:05 EST 2014


On 1/1/2014 1:48 AM, Chris Angelico wrote:
> On Wed, Jan 1, 2014 at 5:39 PM, Travis McGee <nobody at gmail.com> wrote:

What OS? If Windows, did you install the -py3k version for 3.x?

>> Anyway, I finally got it installed, but when I try to use a statement of the
>> sort ser.write("string") I get an exception which seems to imply that the
>> argument needs to be an integer, rather than a string.

According to a Stackoverflow issue, .write(n) will write n 0 bytes 
because it will send bytes(n) == n * bytes(b'\0').

PySerial is written in Python, so you could look at the .write method of 
the Serial class (presuming that 'ser' is an instance thereof) to see 
what it does.

> Quoting the full exception would help!
>
> My suspicion is that it works with byte strings, not Unicode strings.

That is what the doc either says or implies.

> So you could do:
>
> ser.write(b"string")
>
> or:
>
> ser.write("string".encode())
>
> to turn it into a stream of bytes (the latter uses UTF-8, the former
> would use your source file encoding).

-- 
Terry Jan Reedy




More information about the Python-list mailing list