Parsing a setup file

James Stroud jstroud at mbi.ucla.edu
Tue Apr 3 19:29:23 EDT 2007


Tommy Grav wrote:
> Hi,
> 
>   I have a setup file for some numerical simulation code written in  C 
> that looks like this:
> 
> dt 0.1
> time 0.0
> nupdate 10
> noutput 100
> ntotal 10000
> G 39.476926421373015
> Sun 1.00000597682
> mplanet 9.547861040430418e-4
> 3.409530427945 3.635870038323 .03424028779975
> -2.0471057839802485 2.0178211484578044 -9.730193916219667e-4
> mplanet 2.8558373315055975e-4
> 6.612079829705 6.386934883415 -.1361443021015
> -1.5268292602445992 1.4623064051166743 6.108354829704997e-3
> mplanet 4.372731645458918e-5
> 11.16769742623 16.04343604329 .3617849409933
> -1.1927379555398092 .7563317049955387 -7.950313544811802e-3
> particle
> 5.0  0.2  10.5
> 0.0  0.0  10.0
> particle
> 6.0 0.1    5.5
> 0.0 180.0 -10.0
> 
> there can be any number of mplanet and particle enteries in the the  file.
> As I am working on porting this code to python I am trying to figure out
> an efficient way of parsing such data into the program. I have the  freedom
> to play around with the setup file(s) which is nice. I have played  
> around with
> cfgparse, which I like, and made a file like this
> 
> [DEFAULT]
> dt = 0.1
> time = 0.0
> 
> and so on, but that does not give me a good way of parsing in the  list of
> mplanets and particles. I can write my own little parser to handle a  file
> that contains only the mplanets or particles, but I am wondering if  
> there are
> any parsers out there that will handle this type of data? Or is there a
> way to organize my setup file that would simplify the input that I am  
> missing?
> 
> Cheers
>   Tommy

pyaml is good for this kind of thing. No parser needed.


Also, you may be mistaken about ConfigParser, you just need
to indent line continuations (and who says the syntactical meaning of 
whitespace is not a good thing?). E.g.:


euler 6% cat test.conf
[stuff]
mplanet = 4.372731645458918e-5
           11.16769742623 16.04343604329 .3617849409933
           -1.1927379555398092 .7563317049955387 -7.950313544811802e-3



py> from ConfigParser import ConfigParser
py> c = ConfigParser()
py> c.read('test.conf')
['test.conf']
py> c.items('stuff')

[('mplanet',
   '4.372731645458918e-5\n11.16769742623 16.04343604329 
.3617849409933\n-1.1927379555398092 .7563317049955387 
-7.950313544811802e-3')]

James



More information about the Python-list mailing list