Search code examples
numpygpib

numpy and scanf equivalents, turning binary output stream into an array


I am using linux-gpib library to talk to bench equipment. I can ask the device for output from it's buffer, and it streams to std out. I use something like:

import gpib 

gpib.write(16,"FORM3;OUTPDATA;") #FORM3 is binary

data=gpib.read(16,10000)

I'm not sure what the output format looks like, I forgot how the data is delimited. But I figure I need to do some kind of scanf function to grab the floats and out them into an array.

I installed numpy, and think there should be a way to ask python to grab the floats from the stream and put them into an array.

Google hasn't helped much, numpy is really new to me. I know the MATLAB and C command OK.


Solution

  • If you read the data to a string, as you did above, use numpy.fromstring:

    data = '1 2 3 4 5 6 7 8'
    print np.fromstring(data, sep=' ')
    # [ 1.  2.  3.  4.  5.  6.  7.  8.]
    

    Typically in Python, more general parsing is done with regular expressions rather than scanf. See sscanf in Python