0

example input.dat

[settings]
port = 1234
host = abc.com

How can I parse the file, and assign 1234 to agrv[1], abc.com to argv[2] and so on

here is what i tried:

$python p.py input.dat
Traceback (most recent call last):
  File "p.py", line 8, in <module>
    print config['settings']['host']
AttributeError: ConfigParser instance has no attribute '__getitem__'

p.py

  #!/usr/bin/env python
    import sys
    import ConfigParser

    if __name__ == '__main__':
        config = ConfigParser.ConfigParser()
        config.read(sys.argv[1])
        print config['settings']['host']
        print config['settings']['port']

I don't want to use python3 if I can help it.

johndburger
  • 58
  • 1
  • 6
kamal
  • 9,637
  • 30
  • 101
  • 168
  • Note: If you weren't opposed to Python 3, as of Python 3.2, `configparser` [would support the exact approach you're trying to use](https://docs.python.org/3/library/configparser.html#mapping-protocol-access). – ShadowRanger Dec 05 '17 at 21:11

1 Answers1

1

ConfigParser does not support dict-like lookup. After parsing the file, you retrieve values using its get() method, which takes two arguments, the names of the section and option. So:

config = ConfigParser.ConfigParser()
config.read(sys.argv[1])
print config.get('settings', 'host')
print config.get('settings', 'port')

More info here: https://docs.python.org/2/library/configparser.html#configparser-objects

johndburger
  • 58
  • 1
  • 6
  • 1
    Note: On Python 3.2+, [`dict`-like lookup is supported](https://docs.python.org/3/library/configparser.html#mapping-protocol-access). If you're writing new code, there is very little reason to avoid moving to Python 3. – ShadowRanger Dec 05 '17 at 21:12
  • @johndburger so can I do something like $cat test.txt | python p.py , so I don't have to type the arguments, but take them from test.txt – kamal Dec 06 '17 at 10:06
  • @kamal That's a separate issue, but yes, you can do that. If you want to allow for either reading the config from stdin _or_ taking it from the command line, I recommend the file inputs module. This would let you write something like this: `config.readfp(fileinput.input())` (Note the switch to the readfp() method.) And then you can write either of these on the command line: `$ cat test.txt | python p.py` or `$ python p.py test.txt` More about fileinput here: https://docs.python.org/2/library/fileinput.html – johndburger Dec 07 '17 at 15:06