Skip to content

Instantly share code, notes, and snippets.

@tsibley
Created October 24, 2022 23:13
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 tsibley/c5ab5107d718afcc15c741997700f70a to your computer and use it in GitHub Desktop.
Save tsibley/c5ab5107d718afcc15c741997700f70a to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import click
from configparser import ConfigParser
@click.command()
@click.argument("file", type = click.File(), metavar = "<file>")
@click.argument("section", metavar = "<section>")
@click.argument("option", metavar = "<option>")
@click.argument("value", metavar = "<value>", required = False)
@click.pass_context
def ini(ctx, file, section, option, value = None):
"""
Reads an INI config <file> and prints the value of <section>'s <option> or sets it to <value> (if provided).
"""
config = ConfigParser()
config.read_file(file)
if value is None:
try:
value = config[section][option]
except KeyError:
ctx.exit(1)
else:
click.echo(value)
else:
if value:
if section not in config:
config.add_section(section)
config[section][option] = value
else:
try:
del config[section][option]
except KeyError:
ctx.exit(1)
with open(file.name, "w") as f:
config.write(f)
if __name__ == '__main__':
ini()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment