Rotolux

Physics, Python programming, Miscellaneous geekness

Pasting syntax-highlighted code

I just found this guide on pasting syntax highlighted code (escaped with this form) into Blogger blogs. It's probably not all that useful, but anyway, let's give it a go with a function I use to read a binary file output by xmds into Python:


def read_file(indat_fname, xsil_fname):
# get datafile name and precisions
if got_lxml:
with open(xsil_fname) as xml:
xsil = objectify.parse(xml).getroot()
ulong_len = xsil.XSIL.Array[1].Stream.Metalink.get("UnsignedLong")
precision = xsil.XSIL.Array[1].Stream.Metalink.get("precision")
else:
xml = open(xsil_fname).read()
ulong_len = str(xml2obj.xml2obj(xml).XSIL[0].Array[1].Stream.Metalink.UnsignedLong)
precision = str(xml2obj.xml2obj(xml).XSIL[0].Array[1].Stream.Metalink.precision)
ulong_type = {'uint32':'<u4','uint64':'<u8'}[ulong_len]
float_type = {'single':'<f4','double':'<f8'}[precision]

with open(indat_fname,'rb') as f:
xlen = fromfile(f, ulong_type, 1)[0]
xs = fromfile(f, float_type, xlen)
ylen = fromfile(f, ulong_type, 1)[0]
ys = fromfile(f, float_type, ylen)
zlen = fromfile(f, ulong_type, 1)[0]
zs = fromfile(f, float_type, zlen)

rlen1 = fromfile(f, ulong_type, 1)[0]
reals1 = fromfile(f, float_type, rlen1)
ilen1 = fromfile(f, ulong_type, 1)[0]
imags1 = fromfile(f, float_type, ilen1)
psi1 = (reals1+1j*imags1).astype(np.complex64).reshape(xlen,ylen,zlen)
del reals1, imags1

rlen2 = fromfile(f, ulong_type, 1)[0]
reals2 = fromfile(f, float_type, rlen2)
ilen2 = fromfile(f, ulong_type, 1)[0]
imags2 = fromfile(f, float_type, ilen2)
psi2 = (reals2+1j*imags2).astype(np.complex64).reshape(xlen,ylen,zlen)
del reals2, imags2

return psi1, psi2


which sort of works, except for the wrapping - maybe I did something wrong with the template. I'll have another go one day (maybe)