[Tutor] curious struct problem
Marcus Goldfish
magoldfish at gmail.com
Mon Feb 5 15:03:32 CET 2007
On 2/2/07, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
>
> > I'm trying to read a binary file using struct. This code works
> > interactively in the IPython shell, but not as a function invoked from a
> > command line (Windows). Can someone point out my error? Thanks!
>
> Hi Marcus,
>
> There is something very suspicious in the code. You don't happen to have
> any global variables in your program, do you?
>
> Let me underline what you might want to look at.
>
>
> > def demux(filename, channel, nchannels):
> ^^^^^^^^
>
Danny,
Sorry, I had a typo. Attached below is the complete code actually copied
from my editor. Notice that it doesn't do anything now, which is fine b.c.
I just want to troubleshoot the problem. The error is reproduced as a
comment below the source. As far as I know, there are no globals; I am
invoking this from a command line prompt: python demux.py foo.bin 1 1
# ---
import struct
def demux(fname, ch=1, nchan=1):
fmt = str(nchan) + 'h' # nchan of short (int16)
blockSize = struct.calcsize(fmt)
# file setup
infile = open(fname, 'rb')
#outfile = open(fname + 'ch' + str(ch), 'wb')
# iterate over data
chunk = infile.read(blockSize)
while chunk:
x = struct.unpack(fmt, chunk)
chunk = infile.read(blockSize)
# file cleanup
# outfile.close()
infile.close()
# -------------------------------------------------------------------------
# main()
# -------------------------------------------------------------------------
def main(argv=None):
if argv is None:
printHelp()
demux(argv[1], int(argv[2]), int(argv[3])) # filename, ch, nchans
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv))
# C:\python\python demux.py demux.py 1 1
# Traceback (most recent call last):
# File "demux.py", line xx, in ?
# sys.exit(main(sys.argv))
# File "demux.py", line xx, in main
# demux(argv[1], int(argv[2]), int(argv[3])) # filename, ch, nchans
# File "demux.py", line xx, in demux
# x = struct.unpack(fmt, chunk)
# struct.error: unpack str size does not match format
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070205/913180b4/attachment.html
More information about the Tutor
mailing list