[Tutor] Converting a string to a byte array

Peter Otten __peter__ at web.de
Sun Sep 24 08:26:07 EDT 2017


Phil wrote:

> Thank you for reading this.
> 
> The following code sends "Fred" to my serial connected device without
> any problems.
> 
> import serial
> 
> ser = serial.Serial('/dev/ttyACM0',9600)
> ser.write(b'Fred\n')
> 
> 
> I'm trying to do the same under pyqt but I'm having trouble converting a
> string to a byte array. This works correctly from the pyqt IDE but not
> from the console. python3 mycode.py generates "typeError: string
> argument without an encoding"
> 
> It's very likely that my method of converting a string to a byte array
> is incorrect. This is my attempt:
> 
> mytext = "Fred"
> mybytes = bytes(mytext)
> byte = byte + '\n'
> ser.write(mybytes)

This is a bit of a mess. Always cut and paste actual code that you want to 
show. If there is an exception include the traceback.
 
> I don't understand why this works from the pyqt IDE but not when run
> from the console. I suppose the IDE is adding the correct encoding. I
> suspect utf8 is involved somewhere.

When you want to convert a string to a byte sequence it is your turn to 
decide about the encoding. With "Fred" even ASCII would work. When Python 
doesn't pick a default you have to specify it yourself, e. g. if you want to 
use UTF-8:

>>> text = "Fred"
>>> text.encode("utf-8")
b'Fred'

In Python 3 you cannot mix str and bytes, so to add a newline your options 
are

>>> (text + "\n").encode("utf-8")  # concatenate text
b'Fred\n'
>>> text.encode("utf-8") + b"\n"  # concatenate bytes
b'Fred\n'

If you want to write only strings it may also be worth trying to wrap the 
Serial instance into a TextIOWrapper:

# untested!
import serial
import io

ser = serial.Serial('/dev/ttyACM0', 9600)
serial_device = io.TextIOWrapper(ser)

print("Fred", file=serial_device)




More information about the Tutor mailing list