0

I am using Jython and wish to import a text file that contains many configuration values such as:

QManager = MYQM
ProdDBName = MYDATABASE

etc.

.. and then I am reading the file line by line.

What I am unable to figure out is now that as I read each line and have assigned whatever is before the = sign to a local loop variable named MYVAR and assigned whatever is after the = sign to a local loop variable MYVAL - how do I ensure that once the loop finishes I have a bunch of global variables such as QManager & ProdDBName etc.

I've been working on this for days - I really hope someone can help.

Many thanks, Bret.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • related: [How can you dynamically create variables in Python via to a while loop?](http://stackoverflow.com/q/5036700/4279) – jfs Apr 25 '13 at 21:40

1 Answers1

1

See other question: Properties file in python (similar to Java Properties)

Automatically setting global variables is not a good idea for me. I would prefer global ConfigParser object or dictionary. If your config file is similar to Windows .ini files then you can read it and set some global variables with something like:

def read_conf():
    global QManager
    import ConfigParser
    conf = ConfigParser.ConfigParser()
    conf.read('my.conf')
    QManager = conf.get('QM', 'QManager')
    print('Conf option QManager: [%s]' % (QManager))

(this assumes you have [QM] section in your my.conf config file)

If you want to parse config file without help of ConfigParser or similar module then try:

my_options = {}
f = open('my.conf')
for line in f:
    if '=' in line:
        k, v = line.split('=', 1)
        k = k.strip()
        v = v.strip()
        print('debug [%s]:[%s]' % (k, v))
        my_options[k] = v
f.close()
print('-' * 20)
# this will show just read value
print('Option QManager: [%s]' % (my_options['QManager']))
# this will fail with KeyError exception
# you must be aware of non-existing values or values
# where case differs
print('Option qmanager: [%s]' % (my_options['qmanager']))
Community
  • 1
  • 1
Michał Niklas
  • 53,067
  • 18
  • 70
  • 114
  • Thanks so much for the advice. I can now do what I wanted. To make things tidier - how would I loop through each line of my config file and set the configuration options without knowing what configuration options were in the config file? – user2267805 Apr 25 '13 at 23:25
  • +1: a dict, ConfigParser, pyjavaproperties or java.util.Properties is the way to go. – jfs Apr 26 '13 at 12:41