Skip to content

Instantly share code, notes, and snippets.

@schuerg
Last active January 27, 2019 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schuerg/c9cb74f2283ac6c4ad56229917e3b064 to your computer and use it in GitHub Desktop.
Save schuerg/c9cb74f2283ac6c4ad56229917e3b064 to your computer and use it in GitHub Desktop.
[Set INI-file value] Sets a value in an INI-file from command line. #python #ini #config
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This script sets a value in an INI-file.
# It uses Python 3 configparser
# https://docs.python.org/3/library/configparser.html
# Simon Schürg
import argparse
import configparser
def setupArgparse():
parser = argparse.ArgumentParser(description='Set a value in an INI-file.')
parser.add_argument('file', metavar='FILE', help='Filepath of the ini-file')
parser.add_argument('section', metavar='SECTION', help='Section in the INI-file')
parser.add_argument('key', metavar='KEY', help='Key which should hold the value')
parser.add_argument('value', metavar='VALUE', help='Value to set')
# parser.add_argument('-v', '--verbose', action='count', help='Verbose output')
args = parser.parse_args()
return args
def setIni(args):
config = configparser.ConfigParser()
config.read(args.file)
if not config.has_section(args.section):
config.add_section(args.section)
config[args.section][args.key] = args.value
with open(args.file, 'w') as configfile:
config.write(configfile)
if __name__ == "__main__":
args = setupArgparse()
setIni(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment