473,791 Members | 3,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

best way to read a configuration file


Hi All,

i am wondering about the best way to read in a configuration file that
goes like:

###########

[users]
source_dir = '/home/karthik/Projects/python'
data_dir = '/home/karthik/Projects/data'
result_dir = '/home/karthik/Projects/Results'
param_file = $result_dir/param_file
res_file = $result_dir/result_file
comment = 'this is a comment'

K = 8
simulate_K = 0

N = 4000
mod_scheme = 'QPSK'

Na = K+2

############### #######

As of now i use config parser and i get this in a dictionary but

a) but i have users.na and not users.Na (all the fields are in lower
case)

b) all the rhs arguements are string, but i have handled this by
trying " try eval(rhs) ... except ..." block

c) Na = 'K+2' though does not work, would like to have Na = 10, but i
get users.na = 'K+2'

d) result_file, param_file should actually be should be with pathname
extensions filled in.

Have looked in c.l.py none one ofthe suggestions was to use
splitlines, this cant handle blank lines, other was to have config.py
...

Hope to get some solution for this ..

with warm regards

karthik
--

-----------------------------------------------------------------------
Karthikesh Raju, email: ka*****@james.h ut.fi
Researcher, http://www.cis.hut.fi/karthik
Helsinki University of Technology, Tel: +358-9-451 5389
Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277
Department of Computer Sc.,
P.O Box 5400, FIN 02015 HUT,
Espoo, FINLAND
-----------------------------------------------------------------------
Jul 18 '05 #1
5 2390
"Karthikesh Raju" <ka*****@james. hut.fi> wrote in message
news:2d******** ****@itl-pc87.hut.fi...

Hi All,

i am wondering about the best way to read in a configuration file that
goes like:

###########

[users]
source_dir = '/home/karthik/Projects/python'
data_dir = '/home/karthik/Projects/data'
result_dir = '/home/karthik/Projects/Results'
param_file = $result_dir/param_file
res_file = $result_dir/result_file
comment = 'this is a comment'

K = 8
simulate_K = 0

N = 4000
mod_scheme = 'QPSK'

Na = K+2

############### #######

As of now i use config parser and i get this in a dictionary but

a) but i have users.na and not users.Na (all the fields are in lower
case)

b) all the rhs arguements are string, but i have handled this by
trying " try eval(rhs) ... except ..." block

c) Na = 'K+2' though does not work, would like to have Na = 10, but i
get users.na = 'K+2'

d) result_file, param_file should actually be should be with pathname
extensions filled in.

Have looked in c.l.py none one ofthe suggestions was to use
splitlines, this cant handle blank lines, other was to have config.py
..

Hope to get some solution for this ..

with warm regards

karthik
--

-----------------------------------------------------------------------
Karthikesh Raju, email: ka*****@james.h ut.fi
Researcher, http://www.cis.hut.fi/karthik
Helsinki University of Technology, Tel: +358-9-451 5389
Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277
Department of Computer Sc.,
P.O Box 5400, FIN 02015 HUT,
Espoo, FINLAND
-----------------------------------------------------------------------

Jul 18 '05 #2
"Karthikesh Raju" <ka*****@james. hut.fi> wrote in message
news:2d******** ****@itl-pc87.hut.fi...

Hi All,

i am wondering about the best way to read in a configuration file that
goes like:

###########

[users]
source_dir = '/home/karthik/Projects/python'
data_dir = '/home/karthik/Projects/data'
result_dir = '/home/karthik/Projects/Results'
param_file = $result_dir/param_file
res_file = $result_dir/result_file
comment = 'this is a comment'

K = 8
simulate_K = 0

N = 4000
mod_scheme = 'QPSK'

Na = K+2

############### #######

As of now i use config parser and i get this in a dictionary but

a) but i have users.na and not users.Na (all the fields are in lower
case)

b) all the rhs arguements are string, but i have handled this by
trying " try eval(rhs) ... except ..." block

c) Na = 'K+2' though does not work, would like to have Na = 10, but i
get users.na = 'K+2'

d) result_file, param_file should actually be should be with pathname
extensions filled in.

Have looked in c.l.py none one ofthe suggestions was to use
splitlines, this cant handle blank lines, other was to have config.py
..

Hope to get some solution for this ..

with warm regards

karthik
--

-----------------------------------------------------------------------
Karthikesh Raju, email: ka*****@james.h ut.fi
Researcher, http://www.cis.hut.fi/karthik
Helsinki University of Technology, Tel: +358-9-451 5389
Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277
Department of Computer Sc.,
P.O Box 5400, FIN 02015 HUT,
Espoo, FINLAND
-----------------------------------------------------------------------


I modified the config parser that is included as an example that ships with
pyparsing, by adding:

iniLines = "\n".join( file("karthik.i ni").readlines( ) )
config = inifile_BNF().p arseString(iniL ines)
pprint.pprint( config.asList() )
for k in config.users.ke ys():
print k,":",config.us ers[k]

This gives the following output:

[['users',
['source_dir ', " '/home/karthik/Projects/python'"],
['data_dir ', " '/home/karthik/Projects/data'"],
['result_dir ', " '/home/karthik/Projects/Results'"],
['param_file ', ' $result_dir/param_file'],
['res_file ', ' $result_dir/result_file'],
['comment ', " 'this is a comment'"],
['K ', ' 8'],
['simulate_K ', ' 0'],
['N ', ' 4000'],
['mod_scheme ', " 'QPSK'"],
['Na ', ' K+2']]]
comment : 'this is a comment'
data_dir : '/home/karthik/Projects/data'
mod_scheme : 'QPSK'
Na : K+2
K : 8
simulate_K : 0
N : 4000
res_file : $result_dir/result_file
result_dir : '/home/karthik/Projects/Results'
source_dir : '/home/karthik/Projects/python'
param_file : $result_dir/param_file

This actually shows the 3 access modes to the results from a pyparsing
parseString() operation:
- as a raw list of tokens (optionally grouped into sublists, giving a parse
tree)
- as an object with attributes (note reference to 'config.users', also
notice that keys are not converted to lower case)
- as a dictionary (access to config.users[k] for each key k)

The 2nd level keys could also be referenced using the form
config.users.da ta_dir, config.users.co mment, etc.

pyparsing also comes with an expression parser and evaluator in its
examples. With some creative merging of the two, I think you could in
fairly short order have a config parser that would handle your Na = K+2 and
res_file = "$result_dir... " config values.

The pyparsing home page is at http://pyparsing.sourceforge.net.

HTH,
-- Paul
Jul 18 '05 #3
Sorry about that last null post, my fingers tripped over the send button
before I started typing my response.

-- Paul
Jul 18 '05 #4
Thankx paul, will have to download pyparsing, will do in a short will
and try your trick, hope it works well :-)

With warm regards

karthik
--

-----------------------------------------------------------------------
Karthikesh Raju, email: ka*****@james.h ut.fi
Researcher, http://www.cis.hut.fi/karthik
Helsinki University of Technology, Tel: +358-9-451 5389
Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277
Department of Computer Sc.,
P.O Box 5400, FIN 02015 HUT,
Espoo, FINLAND
-----------------------------------------------------------------------
Jul 18 '05 #5
I kept this sample from an ealier thread or website. I don't have the
link nor can I give credit to the author. If you have some lattitude
on the exact format of the config file, this may do the trick for you
though:

Python App Macro Lang
class App:
def __init__(self, name):
self._name = name
def name(self):
return self._name

i=123

macrosource = """
print app.name()
i=1
if i==2:
server="interna l.blah.com"
else:
server="externa l.blah.com"

"""

code = compile(macroso urce, '<string>', "exec")
anApp = App('Global App Object')
context = {}

# populate context with fun things
context["app"] = anApp
exec code in context

print "The server is:" + context["server"]
if i != 123:
raise "local variable 'i' changed"

output = """
c:\cygwin\bin\s h -c "python PyAsMacroLang.p y"
Global App Object
The server is:external.bla h.com
"""
Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2111
by: Herve MAILLARD | last post by:
Hi, I have to write a software doing the following : - Load a file (containing data) Data will be display in a Treeview and are typed as following Equipement Bloc Tag It could have for each Equipement, many blocs and for each bloc, many tags.
7
6578
by: | last post by:
In the beginning we had Ini files. Later we had registery files. Now have xml files and our read-only myapp.config file. My question now, is what is the best way to store and load user and machine specific settings for a .NET program? And what classes, or code do we have to do this in C#? I don't think that using the myapp.config is the best choice to store since the file might be read-only if the program is started from a CD ROM, or...
7
11059
by: Jimbo | last post by:
What's the best format to save a configuration file? I'm currently using an INI extension and I write it like a normal ascii file. Is this the best way? I've heard of using XML to create a config file. What would be the best format? Thank you.
7
5987
by: MrNobody | last post by:
I was a Java developer so I'm used to using property files as a means to keep configuration settings for my apps. I'm wondering what options are there with ..NET? Some settings I want to include are like a root directory for a target program on the user's machine my app uses, which they would be prompted to supply at startup. Normally the registry is used for this but I'd rather not use the registry if possible. Isn't there some kind of...
2
2004
by: G. Dean Blake | last post by:
We currently distribute a web application to serveral servers for a customer. We have been putting the connection string in our web.config file under <appSettings> <add key="dbconn.Connectionstring" value="workstation id=server025....... etc. When we deploy the application we have to change the workstation id and source parameters to name the server where the database will be. We tried to simply specify localhost however VS.NET could...
11
2431
by: Tom | last post by:
I am planning on adding a Preferences form to my application and using the Property Grid to display the preferences to the user. What do you think would be the best way to save these preferences out to an XML file? Use the CAB (Configuration Application Block)? Save the preferences in a class object and serialize them out the the XML file? Write them out directly to the XML file? Other ways??? Just want to get some thoughts together......
10
2855
by: Brett | last post by:
If I have many hard coded values such as file paths, file names, timeouts, etc, where is the best place to define them? Meaning, in the case something needs changing for example, rather than running down all the subs or functions that may contain these values, I'd like one place to change them and have that changed reflected in the subs or functions that use those values. I'd like to avoid globals; keeping the values private to only those...
5
1397
by: Ronald S. Cook | last post by:
We have a .NET Win app that runs at 12 different cattle feeding lots. Each lot runs an isolated instance of our app using its own SQL Server instance. For overall settings specific to a feedlot, we're maintaining those values right now in the database. But I'm not sure its the best way to do it. You see, we have a table "tblFeedlot" with about 20 columns BUT then only one record in the table. I thought maybe the table should have...
5
1875
by: Allan Ebdrup | last post by:
I have a webservice in ASP.Net 2.0, I need to store and load a xml configuration file in relation to one of the web methods in my webservice. What's the best place to store and the best way to load my xml configuration file? I can't integrate the settings in web.config, it has to be a seperate file. Kind Regards, Allan Ebdrup
0
9515
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10155
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9995
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6776
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.