Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python read data from Buffer

Tags:

python

buffer

Im a Rookie!

im reading data from a sensor with:

data = ""
dev = os.open("/dev/rtlightsensor0", os.0_RDWR)
data = os.read(dev,16)

print(data)

result: b'1 53 -5 1\n'

I was thinking thats a String but seems to be like a Buffer? Could anyone give me a Tip, how to get the 4 Numbers?

i tried

value1 = data[1]

but the result was a different number..

like image 826
ser co Avatar asked Oct 20 '25 12:10

ser co


2 Answers

After read other's answer, I must make a supplement here.

I just figured out that you want to read text file instead of binary file, so the codes above won't work for your situation, but I have a better way to read instead of use binary read.

file = open("/dev/rtlightsensor0", "r")
line = file.readline()
data = [int(each) for each in line.split())

Here I read file as a string instead of bytes because your file is text file. Try it and you will find it's really concise.

Below is my original answer, if one day you need read binary data, it will work.

I'm also a Rookie!

You didn't describe your question clearly enough, so I can just guess that you have 4 32-bit(4 bytes) int in your file, which you want to read into your program.

os.read is a binary file read function, so the variable data you got is bytes instead of list of number. Python can't infer the length your number as it can be 4 32-bit number or 1 128-bit number or something else, so you need to say it explicitly by some way.

There is also a little problem that your data is big endian or little endian? If your data doesn't come from network communication, I suppose it's little endian. If you find data is wrong(for example, unbelievable large), you can try to convert 'big' into 'little'.

So you can finish your code like this:

dev = os.open("/dev/rtlightsensor0", os.0_RDWR)
raw_data = os.read(dev,16)
data = []
data.append(int.from_bytes(raw_data[0:4], 'little'))
data.append(int.from_bytes(raw_data[4:8], 'little'))
data.append(int.from_bytes(raw_data[8:12], 'little'))
data.append(int.from_bytes(raw_data[12:16], 'little'))
print(data)

But DO NOT do it like that because it's really silly. If you can understand the code above, then you can write it better like this:

dev = os.open("/dev/rtlightsensor0", os.0_RDWR)
raw_data = os.read(dev, 16)
data = [int.from_bytes(raw_data[i * 4: (i + 1) * 4], 'little') for i in range(4)]
print(data)

By the way, it's not wise to read binary data like this. Generally speaking, the package numpy is recommended.

like image 164
HolderRoy Avatar answered Oct 23 '25 00:10

HolderRoy


It is a byte array. You can convert the byte array to string using decode function

>>> test = b'1 53 -5 1\n'
>>> type(test)
<class 'bytes'>
>>> test[0]
49
>>> test_1 = test.decode("utf-8")
>>> test_1[0]
'1'
like image 40
abhilb Avatar answered Oct 23 '25 02:10

abhilb