Setting options from environment variables when using argparse

后端 未结 12 1987
执念已碎
执念已碎 2020-12-08 04:06

I have a script which has certain options that can either be passed on the command line, or from environment variables. The CLI should take precedence if both are present, a

12条回答
  •  自闭症患者
    2020-12-08 04:40

    Thought I'd post my solution as the original question/answer gave me a lot of help.

    My problem is a little different to Russell's. I'm using OptionParser and instead of an environmental variable for each argument I have just one which simulates the command line.

    i.e.

    MY_ENVIRONMENT_ARGS = --arg1 "Maltese" --arg2 "Falcon" -r "1930" -h

    Solution:

    def set_defaults_from_environment(oparser):
    
        if 'MY_ENVIRONMENT_ARGS' in os.environ:
    
            environmental_args = os.environ[ 'MY_ENVIRONMENT_ARGS' ].split()
    
            opts, _ = oparser.parse_args( environmental_args )
    
            oparser.defaults = opts.__dict__
    
    oparser = optparse.OptionParser()
    oparser.add_option('-a', '--arg1', action='store', default="Consider")
    oparser.add_option('-b', '--arg2', action='store', default="Phlebas")
    oparser.add_option('-r', '--release', action='store', default='1987')
    oparser.add_option('-h', '--hardback', action='store_true', default=False)
    
    set_defaults_from_environment(oparser)
    
    options, _ = oparser.parse_args(sys.argv[1:])
    

    Here I don't throw an error if an argument is not found. But if I wish to I could just do something like

    for key in options.__dict__:
        if options.__dict__[key] is None:
            # raise error/log problem/print to console/etc
    

提交回复
热议问题