Search code examples
pythonconfigparser

python how to pass section name in config parser as variable


******testfile.ini file*******
**[TEST]**
val1=1
val2=3

**[TEST1]**
..
..
**[TEST2]**
..
..
**[TEST3]**
..
..

*****testprog.py****

   #!/usr/bin/python

   import sys 
   import ConfigParser 
   import os

   section = sys.args[1]

   parser = ConfigParser.ConfigParser()

   parser.read('testfile.ini') 
   val1 =parser.get('{0}'.format(section),'val1') 
   val2 =parser.get('{0}'.format(section),'val2')

   print "Value 1 {0}".format(val1) 
   print "Value 2 {0}".format(val2)

I do have config file which contains multiple sections . Section name should be passed as variable . i am trying the above code but it failing with error "Invalid Syntax".

Error:

File "./testprog.py", line 14 print val1 ^ SyntaxError: invalid syntax

which obviously i think code above syntax parser.get is invalid. Any suggestions how to pass section name as variable so that it can read from that particular section and display values.

Help will be much appreciated.


Solution

  • I think your code should be called by main program like this, it is working properly. And make sure each section consist of same variable names.

    #!/usr/bin/python
    
    import sys
    import ConfigParser
    import os
    
    section = sys.argv[1]
    
    def test(section):
        parser = ConfigParser.ConfigParser()
    
        parser.read('testfile.ini')
        val1 =parser.get('{0}'.format(section),'val1')
        val2 =parser.get('{0}'.format(section),'val2')
    
        print "Value 1 {0}".format(val1)
        print "Value 2 {0}".format(val2)
    
    if __name__ == "__main__":
        test(section)