AW: Write to a binary file

Grant Edwards grante at visi.com
Thu Apr 5 13:32:21 EDT 2007


On 2007-04-05, Thinker <thinker at branda.to> wrote:

>>> --- START ---
>>> import os
>>>
>>> msg = chr(0x02) + chr(0x36) + chr(0x00) + chr(0x01) + chr(0x0a) +
>>> chr(0xb0) + chr(0x77)
>>>
>>> f = os.open('/dev/pytest', os.O_RDWR)
>>> os.write(f,msg)
>>> os.close(f)
>>>
>>> f = file('/dev/pytest', 'wb')
>>> f.write(msg)
>>> f.close()
>>> --- END ---

I just ran that on my system (2.4.3), and both versions do a
signle write.

>>> The "pytest" device is a very simple device-driver which
>>> prints out (using "printk()") the buffer delivered to the
>>> write function in a hexadecimal format ("Pytest write> [buffer
>>> in hex format]").
>>>
>>> The output was:
>>> --- Start ---
>>> Pytest write> 02 36 00 01 0a b0 77
>>> Pytest write> 02 36 00 01 0a
>>> Pytest write> b0 77
>>> --- END ---
>>>     
>>
>> I'm surprised that the normal file object's write method does
>> that -- especially for a "binary" file.  IMO, it's a bug when a
>> binary file object treats 0x0a differently than other byte
>> values.  But, using the file object to read/write a device is
>> probably not a good idea because of undefined behavior like
>> that.  File objects also do their own buffering, which I
>> suspect isn't what you want.
>>   
> Why not try to create a file object with bufsize = 0 ?
> for ex:
> ---------
> fo = file('/dev/pytest', 'wb', 0)
> fo.write(....)
> fo.close()
> --------

That's worth a try, but I can't get the normal method to fail...

-- 
Grant Edwards                   grante             Yow!  I selected E5... but
                                  at               I didn't hear "Sam the Sham
                               visi.com            and the Pharoahs"!



More information about the Python-list mailing list