|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +from argparse import ArgumentParser |
| 4 | +from configparser import ConfigParser |
| 5 | +from pathlib import Path |
| 6 | +import random |
| 7 | +import sys |
| 8 | + |
| 9 | + |
| 10 | +def generate_data(n, a=0, b=1): |
| 11 | + return [random.randint(a, b) for _ in range(n)] |
| 12 | + |
| 13 | +def main(): |
| 14 | + arg_parser = ArgumentParser(description='test application') |
| 15 | + arg_parser.add_argument('--conf', |
| 16 | + help='configuration file to use') |
| 17 | + arg_parser.add_argument('--verbose', action='store_true', |
| 18 | + help='verbose output') |
| 19 | + options, remaining_options = arg_parser.parse_known_args() |
| 20 | + system_conf = Path.cwd() / 'etc' / 'my_app.conf' |
| 21 | + cfg = ConfigParser() |
| 22 | + cfg['defaults'] = {'n': '1', 'a': '0', 'b': '6'} |
| 23 | + if options.verbose: |
| 24 | + print('application default values:', file=sys.stderr) |
| 25 | + cfg.write(sys.stderr) |
| 26 | + if system_conf.exists(): |
| 27 | + cfg.read('etc/my_app.conf') |
| 28 | + if options.verbose: |
| 29 | + print('system configuration file values:', file=sys.stderr) |
| 30 | + cfg.write(sys.stderr) |
| 31 | + else: |
| 32 | + print(f'missing configuration file {system_conf}', file=sys.stderr) |
| 33 | + if options.conf: |
| 34 | + cfg.read(options.conf) |
| 35 | + if options.verbose: |
| 36 | + print('user configuration file values:', file=sys.stderr) |
| 37 | + cfg.write(sys.stderr) |
| 38 | + cfg_opts = dict(cfg['defaults']) |
| 39 | + arg_parser.set_defaults(**cfg_opts) |
| 40 | + arg_parser.add_argument('n', type=int, nargs='?', |
| 41 | + help='number of random values to generate') |
| 42 | + arg_parser.add_argument('--a', type=int, help='smallest value') |
| 43 | + arg_parser.add_argument('--b', type=int, help='largest value') |
| 44 | + arg_parser.parse_args(remaining_options, options) |
| 45 | + if options.verbose: |
| 46 | + print('final options:', file=sys.stderr) |
| 47 | + print(f'n = {options.n}\na = {options.a}\nb = {options.b}', end='\n\n', |
| 48 | + file=sys.stderr) |
| 49 | + values = generate_data(options.n, a=options.a, b=options.b) |
| 50 | + print('\n'.join(str(value) for value in values)) |
| 51 | + return 0 |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + status = main() |
| 55 | + sys.exit(status) |
0 commit comments