AW: Write to a binary file

Thinker thinker at branda.to
Thu Apr 5 16:55:22 CEST 2007


Grant Edwards wrote:
> On 2007-04-05, Thomi Aurel RUAG A <Aurel.Thomi at ruag.com> wrote:
>
>   
>> A simplified test programm to compare the function for opening
>> a file i used ("file()") and your suggested "os.open()" showed
>> different behaviour.
>>
>> My simple testprogramm:
>>
>> --- 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 ---
>>
>> 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()
--------

-- 
Thinker Li - thinker at branda.to thinker.li at gmail.com
http://heaven.branda.to/~thinker/GinGin_CGI.py




More information about the Python-list mailing list