How Do I Perform Low Level I/o On A Linux Device File In Python?
Solution 1:
According to the os.write
documentation:
Note: This function is intended for low-level I/O and must be applied to a file descriptor as returned by
os.open()
orpipe()
. To write a “file object” returned by the built-in functionopen()
or bypopen()
orfdopen()
, orsys.stdout
orsys.stderr
, use itswrite()
method.
You shouldn't be mixing and matching here. If you use the global function open()
to open a file, then you must only use the file object's read()
and write()
methods. Conversely, if you use os.open()
to open a file, then you must only use os.read()
and os.write()
.
So, try replacing your call to open()
with os.open()
; or, keep the open()
call, and replace os.write(dev, ...)
with dev.write(...)
and replace os.read(dev, ...)
with dev.read(...)
.
Solution 2:
Add an os.lseek()
to seek back to the beginning of the string you wrote. Currently you wrote 16 bytes which advanced the pointer. When you read, you start reading at the current pointer so you need to back it up to the start of what you wrote.
This worked for me:
#!/usr/bin/python
import os
data = "xxxxxxxxxxxxxxxx"
dev = os.open("/dev/sdp1", os.O_RDWR)
os.write(dev,data)
os.lseek(dev,0,os.SEEK_SET)
printos.read(dev,16)
Solution 3:
The problem turned out to be with the device driver. The read()
method registered with the driver's file_operations
invoked copy_to_user()
but then returned 0
instead of the number of bytes copied to userspace.
The C code above "worked" because it didn't actually check the return value of read()
and buff
was getting populated with the response.
Post a Comment for "How Do I Perform Low Level I/o On A Linux Device File In Python?"