Which is the best way to allow configuration options be overridden at the command line in Python?

后端 未结 8 1901
南笙
南笙 2020-12-22 15:13

I have a Python application which needs quite a few (~30) configuration parameters. Up to now, I used the OptionParser class to define default values in the app itself, with

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-22 15:56

    fromfile_prefix_chars

    Maybe not the perfect API, but worth knowing about.

    main.py

    #!/usr/bin/env python3
    import argparse
    parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
    parser.add_argument('-a', default=13)
    parser.add_argument('-b', default=42)
    print(parser.parse_args())
    

    Then:

    $ printf -- '-a\n1\n-b\n2\n' > opts.txt
    $ ./main.py
    Namespace(a=13, b=42)
    $ ./main.py @opts.txt
    Namespace(a='1', b='2')
    $ ./main.py @opts.txt -a 3 -b 4
    Namespace(a='3', b='4')
    $ ./main.py -a 3 -b 4 @opts.txt
    Namespace(a='1', b='2')
    

    Documentation: https://docs.python.org/3.6/library/argparse.html#fromfile-prefix-chars

    Tested on Python 3.6.5, Ubuntu 18.04.

提交回复
热议问题