[Tutor] Another parsing question

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Mar 25 02:21:29 EST 2004

> Isn't it just that the serial port tries to behave like a file 
> object. That's fairly normal I think. So do most other byte
> streams that are used in Python, and it's common to transfer
> text over serial lines. Also, a serial port using RS-232 is set 
> up to send chunks of 7 or 8 bits, which fits 8 bit characters 
> better than integers which are 32 (or 64 if you're lucky) bits 
> wide.

Behaving like a file is one thing, insisting on text is another.
I think it might be the last point thats key, it needs to be an 
8 bit unit so we need to convert the 32 bit int to 4 8 bit chunks.

But normally thats handled by the IO routines...

> I assume that you just send chr(x) where x is your 8 bit
> unsigned integer, and to read, you call ord() on the
> byte you read to convert it to an integer in the range
> 0 to 255.

Yep, thats what I thought initially, then realised thats 
chr() and ord() are just representational issues, its 
exactly the same bit pattern so why should the serial 
port care!

> Files behave like this in Python.
>>> f = file('c:/test.dat', 'wb')
>>> f.write(65)
> Traceback (most recent call last):
>  File "<pyshell#21>", line 1, in -toplevel-
>    f.write(65)
>TypeError: argument 1 must be string or read-only buffer, not int

Which raised alarm bells in my head because what do you do 
if the integer is bigger than 255, or its a float? Converting 
these to string format and back is horribly inefficient. That
sent my off to the docs... where I rediscovered the struct 

To write an integer using struct we can do this:

>>> import struct
>>> f.write(struct.pack('i',42))
>>> f.close
<built-in method close of file object at 0xa04ed60>
>>> f.close()
>>> f = file("bin.bin",'rb')
>>> n = f.read()
>>> n
>>> i = struct.unpack('i',n)
>>> print i

Its a messy intermediate step but at least you can write binary data 
to a file object. If you know the data is byte sized then using 
chr()/ord() will be the easiest route, if its bigger than a byte 
struct is the way to go. - I never thought I'd be wishing for C's 
ability to cast data types in Python!!!

Alan G.

More information about the Tutor mailing list