How do I perform low level I/O on a Linux device file in Python?

I have a device which returns a string in response to commands written to the device file. I am able to write commands to the device and read the return string in C with code that looks like:

int dev = open("/dev/USBDev251", O_RDWR);
write(dev, data, sizeof(data));
read(dev, buff, 16);

I am trying to do the same in Python with:

dev ="/dev/USBDev251", os.O_RDWR)
os.write(dev, data), 16)

The write is successful, but only an empty string is returned. What am I missing here?


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 or pipe(). To write a “file object” returned by the built-in function open() or by popen() or fdopen(), or sys.stdout or sys.stderr, use its write() 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 to open a file, then you must only use and os.write().

So, try replacing your call to open() with; or, keep the open() call, and replace os.write(dev, ...) with dev.write(...) and replace, ...) with

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:

import os

data = "xxxxxxxxxxxxxxxx"
dev ="/dev/sdp1", os.O_RDWR)

Need Your Help

Windows service shut down

winapi service atl shutdown

I use VS6 and ATL with CServiceModule to implement a custom windows service. In case of a fatal error service should shut itself down. Since CServiceModule is available via _Module variable in all ...

Adaptive replacement cache algorithm

algorithm caching cloud policies page-replacement

I'm trying to implement the Adaptative Replacement Cache algorithm but, i'm reading in the literature, and i can't understand the algorithm. Anyone can explain me that algorithm?