question about binary and serial info

Bengt Richter bokr at oz.net
Thu Aug 18 19:25:11 EDT 2005


On 18 Aug 2005 10:42:32 -0700, nephish at xit.net wrote:

>>>> import serial
>>>> ser =3D serial.Serial('/dev/ttyS0', 2400, timeout=3D 10, bytesize=3D8, =
>stopbits=3D1)
>>>> a =3D ser.read(1)
>>>> print a
>^
In general,

    print a

is not a good way to investigate what a is, because print uses str(a)
as a conversion, and when the original a is type str, that doesn't
change the data being fed to the presentation process (which BTW will
encode the characters depending on the coding scheme for your display output,
or other destination encoding info).

    print repr(a)

will get you a string representation of a that is guaranteed to be printable,
so that if a is a str type containing unprintable characters, you will see
them all represented, e.g.,

 >>> a = '\x01\x02\x20\x41\x42\x43\x20\x30\x31\x32'
 >>> print a
 ?? ABC 012
 >>> print repr(a)
 '\x01\x02 ABC 012'

or, interactively, just

 >>> a
 '\x01\x02 ABC 012'

although for convenience None is not printed when evaluated interactively:

 >>> b = None
 >>> b
 >>> print repr(b)
 None

(interactively, it would be a nuisance when invoking functions that don't return results,
since they in actuality do return None by default).

Sometime it is hard to see the separate characters with printables and \-escaped characters
all joined together. list(a) is an easy way to separate them:

 >>> a
 '\x01\x02 ABC 012'
 >>> print list(a)
 ['\x01', '\x02', ' ', 'A', 'B', 'C', ' ', '0', '1', '2']

or just

 >>> list(a)
 ['\x01', '\x02', ' ', 'A', 'B', 'C', ' ', '0', '1', '2']

The trick is to keep in mind that there is some abstraction that is
being represented in various ways, and make allowances for people's
saying "hex" when they mean the binary that the hex (characters
matching [0-9A-Fa-f]) representation is representing, and similarly
with other abstractions (e.g. binary ;-) and their representations (e.g.,
string representations of binary, or DRAM state representations of binary, etc.)

HTH

Regards,
Bengt Richter



More information about the Python-list mailing list